1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| #include <bits/stdc++.h> #define SZ 60 #define LOG 15 #define MAX_N 20000 #define vl vector<lnt> using namespace std; typedef long long lnt; template <class T> inline void read(T &x) { x = 0; int c = getchar(), f = 1; for (; !isdigit(c); c = getchar()) if (c == 45) f = -1; for (; isdigit(c); c = getchar()) (x *= 10) += f*(c-'0'); } lnt a[MAX_N+5]; int n, q, fa[MAX_N+5][LOG+1], dep[MAX_N+5]; vector <lnt> b[MAX_N+5][LOG+1]; vector <int> G[MAX_N+5]; void addedge(int u, int v) {G[u].push_back(v), G[v].push_back(u);} lnt get_mx(vl base) { lnt ret = 0LL; for (int i = SZ; ~i; i--) if (base[i]) if ((ret^base[i]) > ret) ret ^= base[i]; return ret; } vl merge(vl x, vl y) { vl ret = x; for (int i = SZ; ~i; i--) if (y[i]) for (int j = i; ~j; j--) if (y[i]>>j&1) { if (ret[j]) y[i] ^= ret[j]; else {ret[j] = y[i]; break;} } return ret; } void DFS(int u) { b[u][0].resize(SZ+1); for (int i = SZ; ~i; i--) if (a[u]>>i&1) {b[u][0][i] = a[u]; break;} for (int i = 1; i <= LOG; i++) fa[u][i] = fa[fa[u][i-1]][i-1], b[u][i].resize(SZ+1), b[u][i] = merge(b[u][i-1], b[fa[u][i-1]][i-1]); for (int i = 0, v; i < (int)G[u].size(); i++) if ((v = G[u][i]) ^ fa[u][0]) fa[v][0] = u, dep[v] = dep[u]+1, DFS(v); } lnt query(int u, int v) { vl ub, vb; ub.resize(SZ+1), vb.resize(SZ+1); if (dep[u] < dep[v]) swap(u, v); for (int i = LOG; ~i; i--) if (dep[u]-dep[v] >= (1<<i)) ub = merge(ub, b[u][i]), u = fa[u][i]; if (u == v) return get_mx(merge(ub, b[u][0])); for (int i = LOG; ~i; i--) if (fa[u][i]^fa[v][i]) ub = merge(ub, b[u][i]), u = fa[u][i], vb = merge(vb, b[v][i]), v = fa[v][i]; ub = merge(ub, b[u][0]), vb = merge(vb, b[v][0]); return get_mx(merge(merge(ub, vb), b[fa[u][0]][0])); } int main() { read(n), read(q); for (int i = 1; i <= n; i++) read(a[i]); for (int i = 1, u, v; i < n; i++) read(u), read(v), addedge(u, v); for (int i = 0; i <= LOG; i++) b[0][i].resize(SZ+1); DFS(1); while (q--) { int u, v; read(u), read(v); printf("%lld\n", query(u, v)); } return 0; }
|