B. Destruction of a Tree(分析+删边)

题目

题意:

    给定一棵树,每次可以删去度为偶数的点,点删掉后边也没了。判断是否可以把整棵树都删掉。

分析:

    根据树的性质,每个节点只有一个父亲节点。如果在保证儿子节点能删的都删干净后。若该节点的度为奇数,那么必须先删父亲节点再删当前节点。若为偶数,那么必须先删当前节点,后面再删父亲节点。所以我们只需要深搜,在回溯的时候判断是否可以删点,能删就删。当前节点删完后其子节点就可以删了,再广搜删点即可。

#include <iostream>
#include <queue>
#include <vector> 
#include <set>
using namespace std;

set<int> g[200005];
vector<int> ans;

void dfs(int x,int fa)
{
	set<int>:: iterator it;
	for (it = g[x].begin(); it != g[x].end();)
	{
		int z = *it;
		it ++;
		if( z == fa ) continue;
		dfs(z,x);
	}
	if( g[x].size() % 2 == 0 )
	{
		queue<int> q;
		ans.push_back(x);
		for (it = g[x].begin(); it != g[x].end(); it++)
		{
			g[*it].erase(x);
			if( *it == fa ) continue;
			q.push(*it);
		}
		while( !q.empty() )
		{
			int t = q.front();
			q.pop();
			if( g[t].size() % 2 == 0 )
			{
				ans.push_back(t);
				set<int>::iterator it2;
				for (it2 = g[t].begin(); it2 != g[t].end(); it2++)
				{
					g[*it2].erase(t);
					q.push(*it2);
				}
			}
		}
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		int x;
		cin >> x;
		if( x != 0 )
		{
			g[i].insert(x);
			g[x].insert(i);
		}
	}
	dfs(1,0);
	if( ans.size() == n ) 
	{
		cout << "YES" << '\n';
		for (int i = 0; i < n; i++)
		{
			cout << ans[i] << '\n';
		}
	}
	else cout << "NO" << '\n';
	return 0;
}

发布了132 篇原创文章 · 获赞 6 · 访问量 7923

猜你喜欢

转载自blog.csdn.net/weixin_44316314/article/details/104886655