洛谷 P4551 最长异或路径(01字典树+dfs)(好题)

题目链接
在这里插入图片描述
思路:求最大异或我们考虑01字典树,但是在树上怎么建呢?我们考虑一下树上一点u,点u到其他点的最大异或和路径可以通过边dfs边建字典树的方式进行。

#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
const int maxn=2e5+5;
typedef long long ll;
vector<pair<int,int> >g[maxn];
ll tree[maxn*32][2],tot,ans;
void insert(ll x)
{
	int u=0;
	for(int i=30;i>=0;--i)
	{
		int t=(((1LL<<i)&x)?1:0);
		if(!tree[u][t]) tree[u][t]=++tot;
		u=tree[u][t];
	}
}
ll query(ll x)
{
	int u=0;
	ll res=0;
	for(int i=30;i>=0;--i)
	{
		int t=(((1LL<<i)&x)?1:0);
		if(tree[u][t^1]) u=tree[u][t^1],res+=(1LL<<i);
		else u=tree[u][t];
	}
	return res;
}
void dfs(int x,int fa,ll sum)
{
	ans=max(ans,query(sum));
	for(int i=0;i<g[x].size();++i)
	{
		int to=g[x][i].first;
		if(to==fa) continue;
		ll t=sum^g[x][i].second;
		insert(t);
		dfs(to,x,t);
	}
}
int main()
{
	int n,u,v,w;
	scanf("%d",&n);
	for(int i=0;i<n-1;++i)
	{
		scanf("%d %d %d",&u,&v,&w);
		g[u].push_back({v,w});
		g[v].push_back({u,w});
	}
	insert(0);
	dfs(1,-1,0);
	printf("%lld\n",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值