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 }

猜你喜欢

转载自www.cnblogs.com/wangyiming/p/9071505.html