AcWing 846. 树的重心
原题链接
简单
作者:
CarpeDime
,
2020-08-13 22:01:19
,
所有人可见
,
阅读 364
C++ 代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010, M = N * 2;
int n;
int h[N], e[M], ne[M], idx;
int ans = N;
bool st[N];
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a]= idx ++;
}
// 以u为根的子树中点的数量
int dfs(int u) {
st[u] = true;
int size = 0, sum = 1;
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (st[j]) continue;
int s = dfs(j); // 用s表示当前子树的大小
size = max(size, s);
sum += s;
}
size = max(size, n - sum);
ans = min(ans, size);
return sum;
}
int main() {
scanf("%d", &n);
memset(h, -1, sizeof h);
for (int i = 0; i < n - 1; ++ i) {
int a, b;
scanf("%d%d", &a, &b);
add(a, b), add(b, a);
}
dfs(1);
printf("%d", ans);
return 0;
}