P4551 最长异或路径

#include<cstdio>
#include<iostream>
#include<cstring> 
using namespace std;
const int N=2000005;
int head[N],sum[N],ch[N<<1][2];
int cnt;
int n;
int tot;
int val[N<<1];
struct node{
	int to,next,w;
}edge[N<<1];
void add(int u,int v,int w){
	edge[tot].to=v;
	edge[tot].next=head[u];
	edge[tot].w=w;
	head[u]=tot++;
}
void dfs(int u,int fa){
	for(int i=head[u];i!=-1;i=edge[i].next){
		int v=edge[i].to;
		if(v==fa) continue;
		sum[v]=sum[u]^edge[i].w;
		dfs(v,u);
	}
}
void build(int x){
	int u=0;
	for(int i=30;i>=0;i--){
		int id=(x>>i)&1;
		if(ch[u][id]==0) ch[u][id]=++cnt;
		u=ch[u][id];
	} 
}
int query(int x){
	int u=0 , ans = 0;
	for(int i=30;i>=0;i--){
		int id=(x>>i)&1;
		if(ch[u][id^1]){
			u=ch[u][id^1];
			ans |= (1<<i);
		}
		else u=ch[u][id];
	}
	return ans;
}
int main(){
	memset(head,-1,sizeof(head));
	scanf("%d",&n);
	for(int i=1;i<n;i++){
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		add(u,v,w); add(v,u,w);
	}
	dfs(1,-1);
	for(int i=1;i<=n;i++) build(sum[i]);
	int anss=0;
	for(int i=1;i<=n;i++) anss=max(anss,query(sum[i]));
	printf("%d",anss);
	return 0;
} 
posted @ 2021-11-18 21:31  dfydn  阅读(31)  评论(0编辑  收藏  举报