The xor-longest Path POJ - 3764(树上01字典树)

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§=\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)

在树上找出一条路径使得这条路径上边权异或值最大。
01字典树那一块是一样的。就是在树上跑的时候,异或的东西不一样。
假如说x->u->v的异或值最大,那么我们在求得时候应该是将lca(x,v)到根节点的异或值给省略掉。所以我们应该在树上跑dfs的时候,应该是不断的用跑过的前缀异或值去求最值的。
代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#define ll long long
using namespace std;

const int maxx=1e5+100;
struct node{
	int trie[2];
	int num;
}p[maxx*32];
struct edge{
	int v;
	int w;
	int next;
}e[maxx<<1];
int head[maxx<<1];
int tot,ttot,n,ans;

inline void add(int u,int v,int w)
{
	e[tot].v=v,e[tot].w=w,e[tot].next=head[u],head[u]=tot++;
}
inline void init()
{
	for(int i=0;i<=ttot;i++)
	{
		p[i].trie[0]=p[i].trie[1]=0;
		p[i].num=0;
	}
	tot=0;
	ttot=0;
	memset(head,-1,sizeof(head));
	ans=0;
}
inline void Insert(int x)
{
	int root=0;
	int id;
	for(int i=32;i>=0;i--)
	{
		id=(x>>i)&1;
		if(!p[root].trie[id]) p[root].trie[id]=++ttot;
		root=p[root].trie[id];
	}
	p[root].num=x;
}
inline int Find(int x)
{
	int root=0;
	int id;
	for(int i=32;i>=0;i--)
	{
		id=(x>>i)&1;
		if(p[root].trie[id^1]) root=p[root].trie[id^1];
		else root=p[root].trie[id];
	}
	return p[root].num^x;
}
inline void dfs(int u,int f,int c)
{
	Insert(c);
	for(int i=head[u];i!=-1;i=e[i].next)
	{
		int to=e[i].v;
		if(to==f) continue;
		ans=max(ans,Find(c^e[i].w));//类似于求了一个前缀。
		dfs(to,u,c^e[i].w);
	}
}
int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		init();
		int l,r,w;
		for(int i=1;i<n;i++)
		{
			scanf("%d%d%d",&l,&r,&w);
			l++;r++;
			add(l,r,w);
			add(r,l,w);
		}
		dfs(1,0,0);
		printf("%d\n",ans);
	}
	return 0;
}

努力加油a啊,(o)/~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

starlet_kiss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值