AcWing 846. 树的重心
原题链接
简单
作者:
Value
,
2020-05-25 23:43:51
,
所有人可见
,
阅读 580
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 1E5 + 10;
int head[N], value[N*2], nxt[N*2];
int n, idx;
void add(int a, int b){
value[idx] = b;
nxt[idx] = head[a];
head[a] = idx ++ ;
}
void read(){
memset(head, -1, sizeof head);
scanf("%d", &n);
int a, b;
for(int i = 0; i < n - 1; i ++ ){
scanf("%d%d", &a, &b);
add(a, b), add(b, a);
}
}
int ans = N;
bool st[N];
int dfs(int u){
st[u] = true;
int sum = 1;
int res = 0;
for(int i = head[u]; i != -1; i = nxt[i]){
int p = value[i];
if(st[p]) continue;
int son = dfs(p);
res = max(son, res);
sum += son;
}
res = max(res, n - sum);
ans = min(res, ans);
return sum;
}
int main(){
read();
dfs(1);
cout << ans << endl;
return 0;
}