Files
python/TangDou/AcWing/GraphDfs/846.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

42 lines
1.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}