小G有一个大树

思路

树的重心,经典的问题了,我们只要用一个数组来统计当前节点的儿子个数即可,然后按照题目更新答案。

代码

/*
  Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>

#define mp make_pair
#define pb push_back
#define endl '\n'
#define mid (l + r >> 1)
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define ls rt << 1
#define rs rt << 1 | 1

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;

const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;

inline ll read() {
    ll f = 1, x = 0;
    char c = getchar();
    while(c < '0' || c > '9') {
        if(c == '-')    f = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9') {
        x = (x << 1) + (x << 3) + (c ^ 48);
        c = getchar();
    }
    return f * x;
}

const int N = 1e3 + 10;

vector<int> G[N];

int n, sz[N], ans, sum = inf;

void dfs(int rt, int fa) {
    sz[rt] = 1;
    int maxn = 0;
    for(int i : G[rt]) {
        if(i == fa) continue;
        dfs(i, rt);
        maxn = max(sz[i], maxn);//记录最大的儿子。
        sz[rt] += sz[i];
    }
    maxn = max(maxn, n - sz[rt]);//父节点当成一棵树时候的sz大小。
    if(maxn <= sum) {
        if(maxn < sum) ans = rt;
        else if(rt < ans) ans = rt;
        sum = maxn;
    }
}

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    n = read();
    for(int i = 1; i < n; i++) {
        int x = read(), y = read();
        G[x].pb(y);
        G[y].pb(x);
    }
    dfs(1, 0);
    cout << ans << " " << sum << endl;
    return 0;
}