You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.1 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 100010, M = 200010;
const int INF = 0x3f3f3f3f;
int ans = INF;
bool st[N];
int n;
int h[N], e[M], ne[M], idx;
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int dfs(int u) {
st[u] = 1;
int sum = 1;
int res = 0;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (!st[v]) {
int s = dfs(v); // v子树有多少个节点
sum += s; // 儿子们的节点个数累加和,再加自己的1就是u子树的节点个数sum和
res = max(res, s); // 猴子选大王
}
}
res = max(res, n - sum); // 套路:除了自己的所有猴子,还要考虑反向子树
ans = min(ans, res); // 最大中选最小,就是树的重心
return sum;
}
int main() {
memset(h, -1, sizeof h);
cin >> n; // n个顶点
for (int i = 1; i < n; i++) { // n-1条边
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
dfs(1);
cout << ans << endl;
return 0;
}