Codeforces 964D - Destruction of a Tree(思维 + DFS)

关键点:自底向上检查度数时若发现某一节点为偶数,同时可以destory此节点的子树。

因为当前节点删去后,子节点度数-1可删去,孙子节点同理。

#include 

using namespace std;
const int maxn = 200005;

struct Edge {
    int to, next;
}e[maxn*2];
int head[maxn], tot;
int fa[maxn], deg[maxn];
vector topo, ans;
bool vis[maxn];

void init() {
    //ans.clear();
    //topo.clear();
    //memset(deg, 0, sizeof(deg));
    //memset(vis, 0, sizeof(vis));
    tot = 0;
    memset(head, -1, sizeof(head));
}

void AddEdge(int from, int to) {
    e[tot].to = to;
    e[tot].next = head[from];
    head[from] = tot++;
}

void dfs(int u, int p) {
    if(p != 0) deg[u]++;
    fa[u] = p;
    for(int i = head[u]; i != -1; i = e[i].next) {
        int v = e[i].to;
        if(v != p) {
            deg[u]++;
            dfs(v, u);
        }
    }
    topo.push_back(u);
}

void destory(int u) {
    vis[u] = true;
    ans.push_back(u);
     for(int i = head[u]; i != -1; i = e[i].next) {
        int v = e[i].to;
        if(v != fa[u] && !vis[v]) {
            destory(v);
        }
    }
}

int main() {
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    int n;
    init();
    scanf("%d", &n);
    int p;
    for(int i = 1; i <= n; ++i) {
        cin >> p;
        if(p) AddEdge(p, i), AddEdge(i, p);
    }
    dfs(1, 0);
    //for(int i = 1; i <= n; ++i) printf("deg[%d] = %d, fa[%d] = %d\n", i, deg[i], i, fa[i]);
    //printf("topo: "); for(int i = 0; i < topo.size(); ++i) cout << topo[i]; cout << endl;
    for(int i = 0; i < topo.size(); ++i) {
        int u = topo[i];
        if(deg[u] % 2 == 0 && !vis[u]) {
            deg[fa[u]]--;
            destory(u);
        }
    }
    //printf("ans: "); for(int i = 0; i < ans.size(); ++i) printf("%d", ans[i]); cout << endl;
    if(ans.size() != n) puts("NO");
    else {
        puts("YES");
        for(int i = 0; i < ans.size(); ++i) {
            printf("%d\n", ans[i]);
        }
    }
    return 0;
}

你可能感兴趣的:(Codeforces)