The xor-longest Path POJ - 3764 字典树异或
//#include<bits/stdc++.h> //#pragma comment(linker, "/STACK:1024000000,1024000000") #include<stdio.h> #include<algorithm> #include<queue> #include<string.h> #include<iostream> #include<math.h> #include<set> #include<map> #include<vector> #include<iomanip> using namespace std; #define ll long long #define pb push_back #define FOR(a) for(int i=1;i<=a;i++) const int inf=0x3f3f3f3f; const int maxn=1e5+9; const int maxnode=32*maxn; struct EDGE{ int v,w,next; }G[maxn<<1]; int head[maxn],tot; void init(){memset(head,-1,sizeof head);tot=0;} void addedge(int u,int v,int w){ ++tot;G[tot]={v,w,head[u]};head[u]=tot; } int val[maxn]; //1路径异或到每个数的值 void dfs(int u,int fa,int dis){ val[u]=dis; for(int i=head[u];~i;i=G[i].next){ if(fa==G[i].v)continue; dfs(G[i].v,u,dis^G[i].w); } } int ch[maxnode][2]; int sz; void trinit(){memset(ch[0],0,sizeof ch[0]);sz=1;} void insert(int num){ int u=0; for(int i=30;i>=0;i--){ int v=(num>>i)&1; if(!ch[u][v]){ memset(ch[sz],0,sizeof ch[sz]); ch[u][v]=sz++; } u=ch[u][v]; } } int query(int num){ int u=0,ans=0; for(int i=30;i>=0;i--){ int v=((num>>i)&1)^1; if(ch[u][v]){ ans|=(1<<i); u=ch[u][v]; }else{ u=ch[u][v^1]; } } return ans; } int main(){ int n; while(~scanf("%d",&n)){ int u,v,w; init(); for(int i=1;i<n;i++){ scanf("%d%d%d",&u,&v,&w); u++;v++; addedge(u,v,w);addedge(v,u,w); } dfs(1,-1,0); trinit(); int ans=0; for(int i=1;i<=n;i++){ ans=max(ans,query(val[i])); insert(val[i]); } printf("%d\n",ans); } }
简单的树上异或,用到a^a=0的性质