poj3764(树上边权异或+转化为字典树上找两个值使其异或和最大)

poj3764
题解:先预处理每个节点到根节点的边权异或和,然后将这些值丢进字典树里,最后转化为找两个数使其异或值最大。
数组开到3e5,而且要链式存图,否则会有各种WA和TLE

#include <iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
typedef long long LL;
const LL mod=1e9+7;
const int maxn=3e5+10;
int n;
int tree[maxn*32][2],cnt;
struct node{
	int to,w;
	int nxt;
}es[maxn<<1];
int read()
{
    int x=0;
    char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    while(ch>='0'&&ch<='9')
    {
        x=x*10+ch-'0';
        ch=getchar();
    }
    return x;
}
int head[maxn],tot;
int d[maxn];
void init()
{
    memset(head,0,sizeof(head));tot=0;
    cnt=0;
    for(int i=0;i<=n*35;i++){
    	tree[i][0]=tree[i][1]=0;
	}
}
void addedge(int u,int v,int w)
{
	++tot;
	es[tot].w=w;
	es[tot].to=v;
	es[tot].nxt=head[u];
	head[u]=tot;
}
void dfs(int u,int fa,int pre)
{
	d[u]=pre;
	for(int i=head[u];i;i=es[i].nxt){
		int to=es[i].to;
		if(to==fa)continue;
		int cap=es[i].w;
		dfs(to,u,pre^cap);
	}
}
void add(int x,int rt)
{
	for(int i=31;i>=0;i--){
		int y=((x>>i)&1);
		if(tree[rt][y]==0){
			tree[rt][y]=++cnt;
		}
		rt=tree[rt][y];
	}
}
int query(int x,int rt)
{
	int res=0;
	for(int i=31;i>=0;i--){
		int y=((x>>i)&1);
		if(tree[rt][y^1]){
			res+=(1<<i);
			rt=tree[rt][y^1];
		}
		else{
			rt=tree[rt][y];
		}
	}
	return res;
}
int main() 
{
    while(scanf("%d",&n)!=EOF){
    	init();
    	int s,e,w;
        for(int i=1;i<=n-1;i++){
        	s=read();e=read();w=read();
        	++s;++e;
        	addedge(s,e,w);addedge(e,s,w);
	    }
		dfs(1,0,0);
		cnt=0;
		int ans=0;
		for(int i=1;i<=n;i++){
			add(d[i],0);
			ans=max(ans,query(d[i],0));
		}
		printf("%d\n",ans);
	}  
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值