CF963B Destruction of a Tree

Posted 王宜鸣

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CF963B Destruction of a Tree相关的知识,希望对你有一定的参考价值。

思路:

根据节点度数的奇偶性确定删除节点的先后顺序,然后进行拓扑排序。

实现:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int MAXN = 200005;
 4 vector<int> G[MAXN], G2[MAXN];
 5 int in[MAXN], n;
 6 int build(int u, int p)
 7 {
 8     if (!G[u].size()) { G2[p].push_back(u); in[u]++; return 1; }
 9     int cnt = 0;
10     for (int i = 0; i < G[u].size(); i++) cnt += build(G[u][i], u);
11     if (cnt & 1) { G2[u].push_back(p); in[p]++; return 0; }
12     else { G2[p].push_back(u); in[u]++; return 1; }
13 }
14 void toposort()
15 {
16     queue<int> q;
17     for (int i = 1; i <= n; i++) if (!in[i]) q.push(i);
18     while (!q.empty())
19     {
20         int x = q.front(); q.pop();
21         cout << x << endl;
22         for (auto it: G2[x])
23         {
24             in[it]--;
25             if (!in[it]) q.push(it);
26         }
27     }
28 }
29 int main()
30 {
31     int x, root;
32     while (cin >> n)
33     {
34         for (int i = 1; i <= n; i++)
35         {
36             G[i].clear(); G2[i].clear();
37         }
38         memset(in, 0, sizeof in);
39         for (int i = 1; i <= n; i++)
40         {
41             cin >> x;
42             if (x) G[x].push_back(i);
43             else root = i;
44         }
45         int ans = build(root, 0);
46         if (G2[0].size()) in[root]--;
47         if (ans & 1)
48         {
49             cout << "YES" << endl;
50             toposort();
51         }
52         else cout << "NO" << endl;
53     }
54     return 0;
55 }

 

以上是关于CF963B Destruction of a Tree的主要内容,如果未能解决你的问题,请参考以下文章

codeforces 963B Destruction of a Tree

CodeForces - 963B Destruction of a Tree (dfs+思维题)

Codeforces 963B Destruction of a Tree 贪心

CF1474C - Array Destruction

Codeforces Round #475 (Div. 2) D. Destruction of a Tree

CF911F Tree Destruction