1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| #include <bits/stdc++.h> using namespace std; using LL = long long; const int N = 1e6 + 1, M = N * 2; int n, u, v; int h[N], e[M], ne[M], idx, sz[N]; void add(int u, int v) { e[++idx] = v, ne[idx] = h[u], h[u] = idx; } int main() { scanf("%d", &n); for (int i = 1; i < n; ++i) { scanf("%d%d", &u, &v); add(u, v), add(v, u); } int sum = 0; function<void(int, int, int)> dfs = [&](int f, int u, int d) { sz[u] = 1; for (int i = h[u]; i; i = ne[i]) { int v = e[i]; if (v != f) { sum += d + 1; dfs(u, v, d + 1); sz[u] += sz[v]; } } }; dfs(0, 1, 0); int ans = 1; LL maxsum = sum; function<void(int, int, LL)> reroot = [&](int f, int u, LL us) { for (int i = h[u]; i; i = ne[i]) { int v = e[i]; if (v != f) { LL vs = us - sz[v] + (n - sz[v]); if (maxsum < vs) maxsum = vs, ans = v; reroot(u, v, vs); } } }; reroot(0, 1, sum); printf("%d\n", ans); return 0; }
|