跳到正文

题解

题解:AT_arc045_c [ARC045C] エックスオア多橋君

RainySoul约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
获赞
2

版本

  1. v1当前

题意

给定一颗树,需要你求出有多少个点对 (u,v)(u,v) 满足 uu 到 vv 路径上的边权异或和为 XX。注意 (1,2)(1,2) 和 (2,1)(2,1) 视为同一个点对。

思路

下面记 (a,b)(a,b) 两点之间的路径异或和为 path(a,b)\text{path}(a,b)。

如果你做过树上两点之间的路径异或和问题的话你可以轻松发现这题有一个很好用的结论:

固定 11 为根节点,那么 path(u,v)=path(1,u)xor⁡path(1,v)\text{path}(u,v)=\text{path}(1,u) \operatorname{xor} \text{path}(1,v)。

简单的推导过程:因为 path(1,LCA⁡(u,v))\text{path}(1, \operatorname{LCA}(u,v)) 这一段被两次异或直接抵消掉了,所以 path(1,u)xor⁡path(1,v)\text{path}(1,u) \operatorname{xor} \text{path}(1,v) 就等于 path(u,LCA⁡(u,v))xor⁡path(v,LCA⁡(u,v))\text{path}(u, \operatorname{LCA}(u,v)) \operatorname{xor} \text{path}(v, \operatorname{LCA}(u,v)) 即 path(u,v)\text{path}(u,v)。

有了这个结论之后此题的做法就呼之欲出了,dfs 预处理出 11 到每个点的路径异或和,统计一下每个值出现过多少次,最后就可以 O(n)O(n) 算了。

时间复杂度 O(n)O(n)。

另有一些细节详见代码注释。

AC code:

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=100010;
struct zyx{
	int to,w;
};
int n,x,d[N];
unordered_map<int,int> cnt;
vector<zyx> e[N];
inline int read(){
	int x=0,f=1;
	char c=getchar();
	while(c<'0'||c>'9'){
		if(c=='-')f=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9'){
		x=x*10+c-'0';
		c=getchar();
	}
	return x*f;
}
void dfs(int now,int fa,int dis){
	d[now]=dis;
	cnt[dis]++;//记录每个 dis 值出现次数
	for(int i=0;i<e[now].size();i++){
		int to=e[now][i].to,w=e[now][i].w;
		if(to!=fa){
			dfs(to,now,dis^w);
		}
	}
}
signed main(){
	n=read(),x=read();
	for(int i=1;i<n;i++){
		int u=read(),v=read(),w=read();
		e[u].push_back((zyx){v,w});
		e[v].push_back((zyx){u,w});
	}
	dfs(1,0,0);
	int ans=0;
	for(int i=1;i<=n;i++){
		ans+=cnt[d[i]^x];
		if((d[i]^x)==d[i])ans--;//此处要注意去除 (u,u) 这样的点对
		// == 的优先级高于 ^,记得打括号
	}
	cout<<ans/2<<'\n';//因为 (1,2) 和 (2,1) 都被计算过一遍,所以 ans/2
	return 0;
}
原文