树的重心
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 100005,M = 200005;
int h[N],e[M],ne[M],idx,n,m,ans = N;
bool st[N];
void add(int a,int b){
e[idx] = b,ne[idx] = h[a],h[a] = idx ++;
}
int dfs(int u){
st[u] = true;
int sum = 1;
int res = 0;
for(int i = h[u]; ~i; i = ne[i]){
int j = e[i];
if(!st[j]){
int s = dfs(j);
res = max(res, s);
sum += s;
}
}
res = max(res,n - sum);
ans = min(res,ans);
return sum;
}
int main(){
memset(h, -1, sizeof h);
cin >> n;
m = n - 1;
while(m --){
int a,b;
cin >> a >> b;
add(a,b);
add(b,a);
}
dfs(1);
cout << ans << endl;
return 0;
}