poj 1655(树形DP求重心)

poj 1655
求树的重心,具体解法看这里
之前题看错了,以为第一个要求重心的个数,其实不是。。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#define ms(i, j) memset(i, j, sizeof i)
#define LL long long
#define db double
using namespace std;
const int MAXN = 20000 + 5, INF = 1000000000;
vector<int> G[MAXN];
int n, ans1, ans2, siz[MAXN];
void dfs(int u, int fa) {
    int blc = 0;
    siz[u] = 1;
    for (int i=0;i<G[u].size();i++) {
        int v = G[u][i];
        if (v != fa) {
            dfs(v, u);
            siz[u] += siz[v];
            blc = max(blc, siz[v]);
        }
    }
    blc = max(blc, n - siz[u]);
    if (ans2 > blc) ans2 = blc, ans1 = u;
}
void clean() {
    ans2 = INF;
    for (int i=0;i<=n;i++) G[i].clear();
}
void solve() {
    clean();
    scanf("%d", &n);
    for (int i=1;i<n;i++) {
        int x, y;
        scanf("%d%d", &x, &y);
        G[x].push_back(y), G[y].push_back(x);
    }
    dfs(1, 0);
    printf("%d %d\n", ans1, ans2);
}
int main() {
    #ifndef ONLINE_JUDGE 
    freopen("1.in", "r", stdin);freopen("1.out", "w", stdout);
    #endif
    int T;
    scanf("%d", &T);
    while (T--) solve();
    return 0;
}
------ 本文结束 ------