P4551&&ybtoj【字符串算法】4章3题【最长异或路径】

本文解析了一道关于计算两点间最长异或路径的算法题目,通过推导距离公式和利用trie数据结构,介绍了如何通过深度优先搜索(DFS)求解并优化存储。展示了C++代码实例来实现该问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最长异或路径

题目

P4551


解析

考虑推一下两个点之间的距离式子: d x , y = d x , L C A ( x , y )    x o r    d L C A ( x , y ) , y d_{x,y}=d_{x,LCA(x,y)}\;xor\;d_{LCA(x,y),y} dx,y=dx,LCA(x,y)xordLCA(x,y),y
再异或上两个 d 1 , L C A ( x , y ) d_{1,LCA(x,y)} d1,LCA(x,y)
d x , y = d 1 , x    x o r    d 1 , y d_{x,y}=d_{1,x}\;xor\;d_{1,y} dx,y=d1,xxord1,y
于是直接DFS求出距离,再采用trie就可以AC了

code:

#include<cstring>
#include<cstdio>
#define rr register int
using namespace std;
struct trie
{
	int ch[3000010][26],bo[3000010],tot=1;
	inline void insert(int s){int p=1;for(rr i=31;i>=0;--i)p=(ch[p][(s>>i)&1])?(ch[p][(s>>i)&1]):(ch[p][(s>>i)&1]=++tot);}
	inline int ask(int s)
	{
		int p=1,ans=0,q;
		for(rr i=31;i>=0;--i){q=((s>>i)&1);if(ch[p][!q])p=ch[p][!q],ans+=(1<<i);else p=ch[p][q];}
		return ans;
	}
}AC;
int n,a[100010],head[100010],to[200010],nxt[200010],w[200010],tot,x,y,z;
inline void add(int x,int y,int z){to[++tot]=y,w[tot]=z,nxt[tot]=head[x],head[x]=tot;}
inline void dfs(int x,int fa){for(rr i=head[x];i;i=nxt[i])if(to[i]!=fa)a[to[i]]=w[i]^a[x],dfs(to[i],x);}
int main()
{
	scanf("%d",&n);
	for(rr i=1;i<n;++i)scanf("%d%d%d",&x,&y,&z),add(x,y,z),add(y,x,z);
	dfs(1,0);
	for(rr i=1;i<=n;++i)AC.insert(a[i]);
	for(rr i=1;i<=n;++i)a[i]=AC.ask(a[i]),a[0]=(a[0]<a[i])?a[i]:a[0];
	printf("%d",a[0]);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值