zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    linux C++ 通讯架构(二)linux相关
    TCP/IP协议分层详解
    公网Ip和私网ip
    IP地址的含义
    IP地址,子网掩码、默认网关,DNS服务器是什么意思?
    Iptables&Firewalld防火墙
    Linux服务器性能评估与优化
    Linux性能优化
    基于mysql-proxy实现mysql读写分离
    linux下搭建NFS服务器
  • 原文地址:https://www.cnblogs.com/wangyiming/p/9071505.html
Copyright © 2011-2022 走看看