首页 > 代码库 > Codeforces 219D. Choosing Capital for Treeland (树dp)

Codeforces 219D. Choosing Capital for Treeland (树dp)

题目链接:http://codeforces.com/contest/219/problem/D

树dp

 1 //#pragma comment(linker, "/STACK:102400000, 102400000") 2 #include <algorithm> 3 #include <iostream> 4 #include <cstdlib> 5 #include <cstring> 6 #include <cstdio> 7 #include <vector> 8 #include <cmath> 9 #include <ctime>10 #include <list>11 #include <set>12 #include <map>13 using namespace std;14 typedef long long LL;15 typedef pair <int, int> P;16 const int N = 2e5 + 5;17 struct Edge {18     int next, to, cost;19 }edge[N << 1];20 int head[N], tot, d[N], ans1[N], ans[N];21 int res[N];22 23 inline void add_edge(int u, int v, int c) {24     edge[tot].next = head[u];25     edge[tot].to = v;26     edge[tot].cost = c;27     head[u] = tot++;28 }29 30 void dfs1(int u, int p) {31     d[u] = 1;32     ans1[u] = 0;33     for(int i = head[u]; ~i; i = edge[i].next) {34         int v = edge[i].to;35         if(v == p)36             continue;37         dfs1(v, u);38         d[u] += d[v];39         ans1[u] += edge[i].cost + ans1[v];40     }41 }42     43 void dfs2(int u, int p) {44     ans[u] += ans1[u];45     for(int i = head[u]; ~i; i = edge[i].next) {46         int v = edge[i].to;47         if(v == p)48             continue;49         ans[v] = ans[u] - ans1[v] - edge[i].cost + !edge[i].cost;50         dfs2(v, u);51     }52 }53 54 int main()55 {56     memset(head, -1, sizeof(head));57     int n, u, v;58     scanf("%d", &n);59     for(int i = 1; i < n; ++i) {60         scanf("%d %d", &u, &v);61         add_edge(u, v, 0);62         add_edge(v, u, 1);63     }64     dfs1(1, -1);65     dfs2(1, -1);66     int Min = N, cnt = 0;67     for(int i = 1; i <= n; ++i) {68         Min = min(Min, ans[i]);69     }70     for(int i = 1; i <= n; ++i) {71         if(ans[i] == Min) {72             res[++cnt] = i;73         }74     }75     printf("%d\n", Min);76     sort(res + 1, res + cnt + 1);77     for(int i = 1; i <= cnt; ++i) {78         printf("%d%c", res[i], i == cnt ? \n:  );79     }80     return 0;81 }

 

Codeforces 219D. Choosing Capital for Treeland (树dp)