牛客练习赛32 B题 Xor Path

链接:https://ac.nowcoder.com/acm/contest/272/B
来源:牛客网

题目描述

给定一棵n个点的树,每个点有权值牛客练习赛32 B题 Xor Path。定义牛客练习赛32 B题 Xor Path表示 牛客练习赛32 B题 Xor Path 到 牛客练习赛32 B题 Xor Path 的最短路径上,所有点的点权异或和。
对于牛客练习赛32 B题 Xor Path,求所有牛客练习赛32 B题 Xor Path的异或和。

输入描述:

第一行一个整数n。
接下来n-1行,每行2个整数u,v,表示u,v之间有一条边。
第n+1行有n个整数,表示每个点的权值牛客练习赛32 B题 Xor Path

输出描述:

输出一个整数,表示所有
牛客练习赛32 B题 Xor Path
的异或和,其中
牛客练习赛32 B题 Xor Path
示例1

输入

复制
4
1 2
1 3
1 4
1 2 3 4

输出

复制
5

说明

牛客练习赛32 B题 Xor Path
再将这6个数异或起来就可以得到答案5了。

备注:

牛客练习赛32 B题 Xor Path
 
题解:
  考虑每个点的经过次数sum=子树经过该点到另一个子树+子树上的点经过该点到外面的点+该点到其他点(就是n-1);
如果sum为奇数则对答案有贡献,偶数没有贡献;最后将是奇数的点的权值异或即可;
参考代码:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define clr(a,val) memset(a,val,sizeof(a))
 4 #define RI register int
 5 #define eps 1e-6
 6 typedef long long ll;
 7 const int INF=0x3f3f3f3f;
 8 inline ll read()
 9 {
10     ll x=0,f=1;char ch=getchar();
11     while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
12     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
13     return x*f;
14 }
15 const int maxn=1e6+10;
16 ll n,u,v,tot,head[maxn],val[maxn];
17 ll cnt[maxn],ans;
18 struct Edge{
19     ll u,v,nxt;
20 } edge[maxn];
21 inline void Init() {clr(head,-1);ans=0;tot=0;clr(cnt,0);}
22 inline void addedge(ll u,ll v)
23 {
24     edge[tot].u=u;
25     edge[tot].v=v;
26     edge[tot].nxt=head[u];
27     head[u]=tot++;
28 }
29 inline void dfs(ll t,ll pre)
30 {
31     cnt[t]=1; ll sum=0;
32     for(ll i=head[t];~i;i=edge[i].nxt)
33     {
34         ll v=edge[i].v;
35         if(v!=pre)
36         {
37             dfs(v,t);
38             sum+=cnt[v]*(cnt[t]-1);
39             cnt[t]+=cnt[v];
40         }
41     }
42     sum+=(cnt[t]-1)*(n-cnt[t])+n-1;
43     if(sum&1) ans^=val[t];
44 }
45 int main()
46 {
47     n=read(); Init();
48     for(ll i=0;i<n-1;++i) { u=read(),v=read();addedge(u,v);addedge(v,u);}
49     for(ll i=1;i<=n;++i) val[i]=read();
50     dfs(1,0);
51     printf("%lld
",ans);
52     return 0;    
53 } 
View Code