CF 964D Destruction Of A Tree Thinking,set

The meaning of the question: a tree with n nodes, operation: delete the vertex with an even degree and all its edges. n<=1e5, ask whether all nodes can be deleted through the operation, if the
operation sequence can be output, otherwise output NO.


Delete vertices of even degree times, that is, delete an even number of edges at a point each time.
If the number of vertices is even, then there will always be an odd edge that will not be deleted, and there must be no solution at this time.


If the number of vertices is even If it is odd, then at least one point has an even degree (because the total degree is even), and there must be a solution.
To delete a leaf node, you must delete its parent node.

Follow the leaves to find the first degree If the point u is an even number, the degrees of all the points in the subtree of u are odd.
Then the degrees of the sons of uu that are deleted at this time become even. The entire subtree u can be deleted continuously.

Continue to find the vertices with the deepest even degree in the upper part of u (even edges). Set maintains the even-degree binary (dep[u], u).

#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> ii;
const int N=2e5+5;
int n, u, v, rt, deg [N], dep [N];
bool fish [N];
vector<int> e[N];
void dfs(int u,int fa,int level)
{
	dep[u]=level;
	for(int i=0;i<e[u].size();i++)
		if (e [u] [i]! = fa)
			dfs(e[u][i],u,level+1);
}
intmain()
{
	//ios::sync_with_stdio(false);
	//cin.tie(0);
	scanf("%d",&n);
	for(int u=1;u<=n;u++)
	{
		scanf("%d",&v);
		if(v==0)
			rt=u;
		else
		{
			e[v].push_back(u);
			e[u].push_back(v);
			deg [u] ++, deg [v] ++;
		}
	}
	if(n%2==0)
	{
		puts("NO");
		return 0;
	}
	puts("YES");
	dfs(rt,0,0);
	set<ii> s;
	for(int i=1;i<=n;i++)
		if (deg [i]%2 == 0)
			s.emplace(ii(-dep[i],i));;
	while(!s.empty())
	{
		ii t=*s.begin();
		s.erase(s.begin());
		int u=t.second;
		printf("%d\n",u);
		vis [u] = true;
		for(int i=0;i<e[u].size();i++)
		{
			int v = e [u] [i];
			if(vis[v])	continue;
			deg [v] -;
			if (deg [v]%2 == 0)
				s.emplace (ii (-dep [v], v));
			else
				s.erase(s.find(ii(-dep[v],v)));
		}	
	}
	return 0;
}
//7
//0 1 2 3 3 3 1


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326401964&siteId=291194637