[Luogu4551] 最长异或路径 [01trie]

题意:求树上最长异或路径 N 1 0 5 N\le 10^5

我个纸张看着题突然就打起了线性基
这种蠢事一定要记录一下

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cctype>
using namespace std;
#define add_edge(a,b,c) nxt[++tot]=head[a],head[a]=tot,to[tot]=b,val[tot]=c
int head[100005]={},to[200005]={},val[200005]={},nxt[200005]={};
int xorsum[100005]={};
int N,tot=0,ans=0,id=0;
bool t;
int pos=0;
int child[3000005][2]={};
void dfs(int x,int fa)
{
	for(int i=head[x];i;i=nxt[i])
	{
		if(to[i]==fa)continue;
		xorsum[to[i]]=xorsum[x]^val[i];
		dfs(to[i],x);
	}
}
void build(int x)
{
	pos=0;
	for(int i=30;i>=0;--i)
	{
		t=x&(1<<i);
		if(!child[pos][t])child[pos][t]=++id;
		pos=child[pos][t];
	}
}
int query(int x)
{
	int ret=0;
	pos=0;
	for(int i=30;i>=0;--i)
	{
		t=x&(1<<i);
		if(child[pos][!t])ret+=(1<<i),pos=child[pos][!t];
		else pos=child[pos][t];
	}
	return ret;
}
int main()
{
	scanf("%d",&N);
	for(int a,b,c,i=1;i<N;++i)
	{
		scanf("%d%d%d",&a,&b,&c);
		add_edge(a,b,c); add_edge(b,a,c);
	}
	dfs(1,0);
	for(int i=1;i<=N;++i)build(xorsum[i]);
    for(int i=1;i<=N;++i)ans=max(ans,query(xorsum[i]));
    printf("%d",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Estia_/article/details/82902766