树形DP
注意拓扑排序避免爆栈
计算所有点到每个点的距离。初始根节点位root
f[i] 表示子树到i点的距离和,g[i] 表示子树外到i点的距离和,sz[i] 表示子树的大小
状态转移方程见代码
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
const int maxn = 2000000;
struct EDGE {
int to, nxt;
} edge[maxn * 2 + 5];
int n, ans, ansi = 1;
int head[maxn + 5], cnt;
int size[maxn + 5];
inline void add(int u, int v) {
edge[++cnt].nxt = head[u];
edge[cnt].to = v;
head[u] = cnt;
}
void dfss(int x, int dep, int pre) {
size[x] = 1; ans += dep;
for (int i = head[x]; i; i = edge[i].nxt) {
int v = edge[i].to;
if (v == pre) continue;
dfss(v, dep + 1, x);
size[x] += size[v];
}
}
void dfs(int x, int pre, int sum) {
if (sum - size[x] + n - size[x] > ans || (sum - size[x] + n - size[x] == ans && x < ansi)) {
ans = sum - size[x] + n - size[x];
ansi = x;
}
//ans = max(ans, sum - size[x] + n - size[x]);
for (int i = head[x]; i; i = edge[i].nxt) {
int v = edge[i].to;
if (v == pre) continue;
dfs(v, x, sum - size[x] + n - size[x]);
}
}
int main() {
int x, y;
scanf("%d", &n);
//size[0] = n;
for (int i = 1; i < n; i++) {
scanf("%d %d", &x, &y);
add(x, y);
add(y, x);
}
dfss(1, 1, 0);
for (int i = head[1]; i; i = edge[i].nxt) {
dfs(edge[i].to, 1, ans);
}
printf("%d\n", ansi);
//for (int i = 1; i <= n; i++) printf("%d %d\n", i, size[i]);
return 0;
}