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 69 70 71 72 73
| #include <bits/stdc++.h> #define F(n) Fi(i,n) #define Fi(i,n) Fl(i,0,n) #define Fl(i,l,n) for(int i=l;i<n;i++) using namespace std; const int N = 1e5+1, Sz = 29; vector<int>G[N]; struct Trie{ static Trie ST[N*Sz],*p; Trie *ch[2]; Trie(){ ch[0] = ch[1] = NULL; } static int get_bit(int x,int h){ return x&(1<<h)?1:0; } Trie* ins(int x, int h = Sz){ if(h<0)return new(Trie::p++) Trie(); int b = get_bit(x,h); Trie *r = new(Trie::p++) Trie(*this); if(!r->ch[b])r->ch[b] = new(Trie::p) Trie(); r->ch[b] = r->ch[b]->ins(x,h-1); return r; } }*R[N], Trie::ST[N*Sz],*Trie::p = Trie::ST; int D[N],ANS[N], st; int get_max(int x, Trie *r){ int h = Sz+1, res = 0; while(h--,h+1){ int b = r->get_bit(x,h); if(r->ch[!b]){ res += 1<<h; r = r->ch[!b]; }else r = r->ch[b]; } return res; } void DFS(int now,int fa, int num, int mx){ int tmp = num^D[now]; ANS[now] = max(mx, get_max(tmp,R[st-1])); R[st] = R[st-1]->ins(tmp); st++; Trie *tmpP = Trie::p; for(int v:G[now])if(v!=fa){ DFS(v,now,tmp,ANS[now]); } Trie::p = tmpP; st--; } main(){ ios_base::sync_with_stdio(false); cin.tie(0); int t,n,a,b; R[0] = new(Trie::p) Trie(); R[0] = R[0]->ins(0); st = 1; cin>>t; while(t--){ cin>>n; F(n)cin>>D[i]; fill(G,G+n,vector<int>()); F(n-1){ cin>>a>>b; a--,b--; G[a].push_back(b); G[b].push_back(a); } DFS(0,-1,0,0); F(n)cout<<ANS[i]<<'\n'; } }
|