codeforces C. Xor-tree
生活随笔
收集整理的這篇文章主要介紹了
codeforces C. Xor-tree
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
http://codeforces.com/problemset/problem/430/C
題意:在一棵上有n個(gè)節(jié)點(diǎn),有n-1條邊,在每一個(gè)節(jié)點(diǎn)上有一個(gè)值0或1,然后給你一個(gè)目標(biāo)樹,讓你選擇節(jié)點(diǎn),然后把節(jié)點(diǎn)的值翻轉(zhuǎn),它的孫子節(jié)點(diǎn)跟著翻轉(zhuǎn),依次類推。。。問(wèn)經(jīng)過(guò)最少次數(shù)可以使這棵樹變成目標(biāo)樹。
思路:利用異或的性質(zhì),任何數(shù)和0異或?yàn)樗旧?#xff0c;從根節(jié)點(diǎn)dfs就行。
1 #include <cstdio> 2 #include <vector> 3 #include <cstring> 4 #include <algorithm> 5 #define maxn 200100 6 using namespace std; 7 8 int n,k,x; 9 int a[maxn]; 10 int b[maxn]; 11 int num[maxn]; 12 bool vis[maxn]; 13 vector<int>g[maxn]; 14 int ans[maxn]; 15 int cnt; 16 void dfs(int c,int x,int y) 17 { 18 if((a[c]^x)!=b[c]) 19 { 20 ans[cnt++]=c; 21 x=!x; 22 } 23 for(int i=0; i<(int)g[c].size(); i++) 24 { 25 int v=g[c][i]; 26 if(!vis[v]) 27 { 28 vis[v]=true; 29 dfs(v,y,x); 30 } 31 } 32 } 33 34 int main() 35 { 36 scanf("%d",&n); 37 for(int i=1; i<n; i++) 38 { 39 int u,v; 40 scanf("%d%d",&u,&v); 41 g[u].push_back(v); 42 g[v].push_back(u); 43 } 44 for(int i=1; i<=n; i++) 45 { 46 scanf("%d",&a[i]); 47 } 48 for(int i=1; i<=n; i++) 49 { 50 scanf("%d",&b[i]); 51 } 52 vis[1]=true; 53 dfs(1,0,0); 54 printf("%d\n",cnt); 55 for(int i=0; i<cnt; i++) 56 { 57 printf("%d\n",ans[i]); 58 } 59 return 0; 60 } View Code?
轉(zhuǎn)載于:https://www.cnblogs.com/fanminghui/p/4314210.html
總結(jié)
以上是生活随笔為你收集整理的codeforces C. Xor-tree的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 数据结构——无向图创建邻接表以及深度遍历
- 下一篇: 1、SVPWM空间矢量脉宽调制和基本原理