1. 程式人生 > >POJ 2378(樹形DP)

POJ 2378(樹形DP)

POJ 2378(樹形DP)

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int MAX = 50010;

struct edge { //建結構體
    int next;
    int to;
}edges[MAX*2];

int head[MAX];//前驅節點
int vis[MAX];//是否訪問過,做標記
int dp[MAX];//記錄擁有最大的節點數
int num[MAX];//統計以每個結點為根的樹的結點數,記為num[].
int n, tot;

void add(int u, int v) { //建樹
    edges[tot].to = v;
    edges[tot].next = head[u];
    head[u] = tot++;
}


void init() {
    tot = 0;
    memset(dp, 0, sizeof(dp));
    memset(vis, 0, sizeof(vis));
    memset(num, 0, sizeof(num));
    memset(edges, 0, sizeof(edges));
    memset(head, -1, sizeof(head));
}


void dfs(int u) {
    vis[u] = 1;
    num[u] = 1;

    for(int i = head[u]; i != -1; i = edges[i].next) {
        int v = edges[i].to;

        if(vis[v])
            continue;

        dfs(v);
        dp[u] = max(dp[u], num[v]);
        num[u] += num[v];

    }

    dp[u] = max(dp[u], n - num[u]);
}

int main() {
    freopen("data.in", "r", stdin);
    int a, b;
    while(~scanf("%d", &n)) {
        init();
        for(int i = 1; i <= n-1; i++) {
            scanf("%d%d", &a, &b);
            add(a, b);
            add(b, a);
        }

        dfs(1);
        int ans[MAX];
        int k = 0;
        for(int i = 1; i <= n; i++) {
            if(dp[i] <= n/2)
                ans[++k] = i;
        }

        for(int i = 1; i <= k; i++) {
            printf("%d\n", ans[i]);

        }
    }

    return 0;
}