429A - Xor-tree - CodeForces Solution


dfs and similar trees *1300

Please click on ads to support us..

Python Code:

n = int(input())
adj_list = {i: [] for i in range(n)}
 
for edge in range(n-1):
    a, b = list(map(int, input().split()))
    adj_list[a-1].append(b-1)
    adj_list[b-1].append(a-1)
 
v = list(map(int, input().split()))
d = list(map(int, input().split()))
 
ans = 0
queue = [[0, 0, 0, 0]] visited = [0 for i in range(n)]
visited[0] = 1
 
lst = []
 
while len(queue) != 0:
    node, even, odd, level = queue.pop()
    if level == 0:
        if (even == 0 and v[node] != d[node]) or (even == 1 and v[node] == d[node]):
            ans += 1
            even = 1 - even
            lst.append(node + 1)
    else:
        if (odd == 0 and v[node] != d[node]) or (odd == 1 and v[node] == d[node]):
            ans += 1
            odd = 1 - odd
            lst.append(node + 1)
    level = 1 - level
 
    for son in adj_list[node]:
        if (visited[son] == 0):
            visited[son] = 1
            queue.append([son, even, odd, level])
 
print(ans)
for i in lst:
    print(i)

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
int init[100005],goal[100005];
vector<int>g[100005],ans;
void dfs(int v,int p,int odd,int even,int h){
	if(h%2==1){
		if(odd==1) init[v]=1-init[v];
		if(init[v]!=goal[v]) ans.pb(v),odd=1-odd;
	}
	else{
		if(even==1) init[v]=1-init[v];
		if(init[v]!=goal[v]) ans.pb(v),even=1-even;
	}
	for(auto it:g[v])
		if(it!=p) dfs(it,v,odd,even,h+1);
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
	int i,n;
	cin>>n;
	for(i=1;i<=n-1;i++){
		int a,b;
		cin>>a>>b;
		g[a].pb(b);
		g[b].pb(a);
	}
	for(i=1;i<=n;i++) cin>>init[i];
	for(i=1;i<=n;i++) cin>>goal[i];
	dfs(1,0,0,0,1);
	cout<<ans.size()<<'\n';
	for(auto it:ans) cout<<it<<'\n';
}


Comments

Submit
0 Comments
More Questions

1374C - Move Brackets
1476A - K-divisible Sum
1333A - Little Artem
432D - Prefixes and Suffixes
486A - Calculating Function
1373B - 01 Game
1187A - Stickers and Toys
313B - Ilya and Queries
579A - Raising Bacteria
723A - The New Year Meeting Friends
302A - Eugeny and Array
1638B - Odd Swap Sort
1370C - Number Game
1206B - Make Product Equal One
131A - cAPS lOCK
1635A - Min Or Sum
474A - Keyboard
1343A - Candies
1343C - Alternating Subsequence
1325A - EhAb AnD gCd
746A - Compote
318A - Even Odds
550B - Preparing Olympiad
939B - Hamster Farm
732A - Buy a Shovel
1220C - Substring Game in the Lesson
452A - Eevee
1647B - Madoka and the Elegant Gift
1408A - Circle Coloring
766B - Mahmoud and a Triangle