木のB.破壊(消去+分析)

タイトル

質問の意味:

    木を考えると、偶数のそれぞれの時点を削除することができ、削除のではない点は、背後にもあります。ツリー全体が削除されているかどうかを確認します。

分析:

    木の性質に応じて、各ノードは、唯一の親ノードを持っています。ノードは、彼の息子を確保するために削除することができればクリーン後に削除されます。ノードの奇数の場合は、最初に親ノードを削除してから、現在のノードを削除する必要があります。それが偶数であれば、あなたは最初に現在のノードを削除する必要があり、その後、削除ノードに父親を追いました。私たちはただ深く検索する必要があるので、削除し、削除するために、ポイントを削除することができるかどうか、時間の背中が決定します。現在のノードを削除した後、その子ノードを削除することができ、その後、削除全体の検索を指します。

#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