[NOIP2012模拟10.22] 最长路径 [01trie]

同luogu4551,数据范围大一倍。
         x o r s u m [ a ] x o r s u m [ b ] \;\;\;\;xorsum[a]\oplus xorsum[b]
= x o r s u m [ a ] x o r s u m [ b ] x o r s u m [ l c a ] x o r s u m [ l c a ] =xorsum[a]\oplus xorsum[b]\oplus xorsum[lca]\oplus xorsum[lca]
利用这个性质建立01trie。

#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[200005]={},to[400005]={},val[400005]={},nxt[400005]={};
int xorsum[200005]={};
int N,tot=0,ans=0,id=0,pos=0;
int son[4000005][2]={};
bool t;
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(!son[pos][t])son[pos][t]=++id;
		pos=son[pos][t];
	}
}
int query(int x)
{
	int ret=0;
	pos=0;
	for(int i=30;i>=0;--i)
	{
		t=x&(1<<i);
		if(son[pos][!t])ret+=(1<<i),pos=son[pos][!t];//改变选择的路径
		else pos=son[pos][t];
	}
	return ret;
}
int main()
{
	scanf("%d",&N);
	for(int x,y,z,i=1;i<N;++i)
	{
		scanf("%d%d%d",&x,&y,&z);
		add_edge(x,y,z);
		add_edge(y,x,z);
	}
	dfs(1,0);
	for(register int i=1;i<=N;++i)build(xorsum[i]);
    for(register int i=1;i<=N;++i)ans=max(ans,query(xorsum[i]));
    printf("%d",ans);
	return 0;
}

猜你喜欢

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