964D - Destruction of a Tree - CodeForces Solution


dfs and similar dp trees *2000

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define mp make_pair
#define pb push_back
#define MAXN 200100
int n, rt, ok[MAXN];
vector<int> e[MAXN];
ll x, y, m, ans;

int dfs(int node, int last)
{
	int sum = 0;
	for(int i = 0; i < e[node].size(); i++)
	if(e[node][i] != last)
	{
		int son_d = dfs(e[node][i], node);
		if(son_d) ok[e[node][i]] = 1;
		else sum++;
	}
	return sum % 2;
}

void dfs2(int node, int last)
{
	int sum = 0;
	for(int i = 0; i < e[node].size(); i++)
	if(e[node][i] != last && ok[e[node][i]])
	{
		dfs2(e[node][i], node);
	}
	else sum++;
	//printf("%d ", sum);
	printf("%d\n", node);
	for(int i = 0; i < e[node].size(); i++)
	if(e[node][i] != last && !ok[e[node][i]])
	{
		dfs2(e[node][i], node);
	}
}

int main()
{
    scanf("%d", &n);
    rep(i, 1, n)
    {
    	int v;
    	scanf("%d", &v);
    	if(v == 0) rt = i;
    	else
    	{
    		e[i].pb(v);
    		e[v].pb(i);
		}
	}
	if(n % 2 == 0)
	{
		printf("NO\n");
		return 0;
	}
	printf("YES\n");
    dfs(rt, 0);
    dfs2(rt, 0);
    return 0;
}


Comments

Submit
0 Comments
More Questions

1382A - Common Subsequence
1512D - Corrupted Array
667B - Coat of Anticubism
284B - Cows and Poker Game
1666D - Deletive Editing
1433D - Districts Connection
2B - The least round way
1324A - Yet Another Tetris Problem
246B - Increase and Decrease
22E - Scheme
1566A - Median Maximization
1278A - Shuffle Hashing
1666F - Fancy Stack
1354A - Alarm Clock
1543B - Customising the Track
1337A - Ichihime and Triangle
1366A - Shovels and Swords
919A - Supermarket
630C - Lucky Numbers
1208B - Uniqueness
1384A - Common Prefixes
371A - K-Periodic Array
1542A - Odd Set
1567B - MEXor Mixup
669A - Little Artem and Presents
691B - s-palindrome
851A - Arpa and a research in Mexican wave
811A - Vladik and Courtesy
1006B - Polycarp's Practice
1422A - Fence