The xor-longest Path(POJ 3764)

The xor-longest Path

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:

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.


这道题首先考你异或的知识;

f(a,b)=f(1,a)^f(1,b) 异或的一种性质;知道了这个,这道题才能写出来;

我们要求异或和最长的路径,我们只要求得根结点到每个点的异或路径,然后转化为在两个集合中找出两个元素异或值最大就行;

这道题不知道是oj的原因还是什么,我的cin关闭了输入输出流还是卡了,用了scanf才过的;

代码:

#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define LL long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
//ios::sync_with_stdio(false);
using namespace std;
const int N=100010;
const int M=200100;
const LL mod=1e9+7;
struct Node{
	int to,nex,w;
}edge[N*2];
int head[N];
int cnt;
void add(int p,int q,int w){
	edge[cnt].to=q;
	edge[cnt].w=w;
	edge[cnt].nex=head[p];
	head[p]=cnt++;
}
int tr[N*32][2],val[N*32],rt;
int mmax=0;
void init(){
	memset(head,-1,sizeof(head));
	cnt=0;
	mmax=0;
	rt=0;
	tr[0][1]=tr[0][0]=0;
}
void add(int p){
	int k=0;
	for(int i=31;i>=0;i--){
		int d=(p>>i)&1;
		if(!tr[k][d]){
			tr[k][d]=++rt;
			val[rt]=0;
			tr[rt][0]=tr[rt][1]=0;
		}
		k=tr[k][d];
	}
	val[k]=p;
}
int search(int p){
	int k=0;
	for(int i=31;i>=0;i--){
		int d=(p>>i)&1;
		if(tr[k][d^1]) k=tr[k][d^1];
		else k=tr[k][d];
	}
	return val[k]^p;
}
void dfs(int fa,int so,int w){
	add(w);
	for(int i=head[so];i!=-1;i=edge[i].nex){
		if(edge[i].to==fa) continue;
		mmax=max(mmax,search(w^edge[i].w));
		dfs(so,edge[i].to,w^edge[i].w);
	}
}
int main(){
//	ios::sync_with_stdio(false);
	int n;
	while(cin>>n){
		init();
		int u,v,w;
		for(int i=1;i<n;i++){
//			cin>>u>>v>>w;
			scanf("%d%d%d",&u,&v,&w);
			add(u,v,w);	
			add(v,u,w);
		}
		dfs(-1,0,0);
		cout<<mmax<<endl;
	} 
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值