牛客練習賽32 B題 Xor Path
連結:https://ac.nowcoder.com/acm/contest/272/B
來源:牛客網
題目描述
給定一棵n個點的樹,每個點有權值 。定義 表示 到 的最短路徑上,所有點的點權異或和。 對於 ,求所有 的異或和。輸入描述:
第一行一個整數n。 接下來n-1行,每行2個整數u,v,表示u,v之間有一條邊。 第n+1行有n個整數,表示每個點的權值 。輸出描述:
輸出一個整數,表示所有
的異或和,其中
。示例1
輸入
複製4 1 2 1 3 1 4 1 2 3 4
輸出
複製5
說明
\mathbb{path}(2,4)=A_2\ \mathbb{xor}\ A_1\ \mathbb{xor}\ A_4=7\\
\mathbb{path}(3,4)=A_3\ \mathbb{xor}\ A_1\ \mathbb{xor}\ A_4=6}" referrerPolicy="no-referrer"> 再將這6個數異或起來就可以得到答案5了。
備註:
題解:
考慮每個點的經過次數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\n",ans); 52 return 0; 53 }View Code