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

· · 题解

题意

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

思路

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

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

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

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

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

时间复杂度 O(n)。

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

AC code:

#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;
}