题目:
样例:
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#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]; //bool数组存遍历过的点
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
//返回以u为根的子树中点的数量
int dfs(int u)
{
st[u] = true; //标记当前的点u已经被搜过
int sum = 1, res = 0; //sum当前点的数量,res存将这个点删除后,剩余各个连通块中点数的最大值
for (int i = h[u]; i != -1; i = ne[i]) //遍历u的所有初边
{
int j = e[i]; //j存当前链表里的节点对应的图里面的点的编号
if (!st[j])
{
int s=dfs(j); //s表示当前子树的大小
res=max(res,s);
sum+=s;
}
}
res = max(res, n - sum ); //该节点的父节点的连通块的大小
ans = min(ans, res);
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\n", ans);
return 0;
}