POJ 3764(dfs+字典树)

The xor-longest Path
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 6132 Accepted: 1328

Description

In an edge-weighted tree, the xor-length of a path p is defined as the xor sum of the weights of edges on p:

_{xor}length(p)=\oplus_{e \in p}w(e)

⊕ is the xor operator.

We say a path the xor-longest path if it has the largest xor-length. Given an edge-weighted tree with n nodes, can you find the xor-longest path?  

Input

The input contains several test cases. The first line of each test case contains an integer n(1<=n<=100000), The following n-1 lines each contains three integers u(0 <= u < n),v(0 <= v < n),w(0 <= w < 2^31), which means there is an edge between node u and v of length w.

Output

For each test case output the xor-length of the xor-longest path.

Sample Input

4
0 1 3
1 2 4
1 3 6

Sample Output

7

Hint

The xor-longest path is 0->1->2, which has length 7 (=3 ⊕ 4)


题目大意:
给出一个无向图,求出异或值最大的路径,输出最大的异或值。


解题思路:

或运算中有(i,v)^(i,u)=(u,v)的定理,因此要求出任意两个点之间的路径的异或值可以先求出每个点到i点的异或值,这可以通过dfs求出,时间复杂度为O(n)。

之后求任意两个点之间的异或值的最大值。如果暴力算的话时间复杂度为O(n^2)明显会超时,因此想到了字典树。

因为最大值不超过2^31,因此把值转换为2进制,分为30层,每层存0或1,每次寻找时从最高位向下找,采取贪心的思想,如果高位异或能有1就直接走该节点。


#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<bitset>
#include<queue>
#include<stack>
#include<list>
#include<set>
#include<math.h>
#include<map>
using namespace std;
int d[6000000][2],cnt;
struct edge
{
	int to,w,next;
	edge(int x,int y,int z):to(x),w(y),next(z){}
	edge(){}
}e[400005];
int num[100005],vis[100005],tot,head[100005];
void addedge(int from,int to,int w)
{
	e[tot]=edge(to,w,head[from]);
	head[from]=tot++;
}
void dfs(int v,int w)
{
	vis[v]=1;
	num[v]=w;
	for(int i=head[v];i!=-1;i=e[i].next)
	{
		if(!vis[e[i].to])
			dfs(e[i].to,w^e[i].w);
	}
}
void add(int x)
{
	int p=1;
	for(int i=30;i>=0;i--)
	{
		if(d[p][(x>>i)&1]==0)
			d[p][(x>>i)&1]=++cnt;
		p=d[p][(x>>i)&1];
	}
}
int find(int x)
{
	int p=1,ans=0;
	for(int i=30;i>=0;i--)
	{
		int t=(x>>i)&1;
		if(d[p][1^t])
		{
			ans+=(1<<i);
			p=d[p][1^t];
		}
		else p=d[p][t];
	}
	return ans;
}
int main()
{
	//freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		tot=0;
		memset(d,0,sizeof(d));
		memset(vis,0,sizeof(vis));
		memset(head,-1,sizeof(head));
		cnt=1;
		for(int i=1;i<n;i++)
		{
		int x,y,w;
		scanf("%d%d%d",&x,&y,&w);
		addedge(x,y,w);
		addedge(y,x,w);
		}
		dfs(0,0);
		int ans=0;
		for(int i=0;i<n;i++)
		{
			add(num[i]);
			ans=max(ans,find(num[i]));
		}
		printf("%d\n",ans);
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值