给定一颗树,树中包含n个结点(编号1~n)和n-1条无向边。
请你找到树的重心,并输出将重心删除后,剩余各个连通块中点数的最大值。
重心定义:重心是指树中的一个结点,如果将这个点删除后,剩余各个连通块中点数的最大值最小,那么这个节点被称为树的重心。
输入格式
第一行包含整数n,表示树的结点数。
接下来n-1行,每行包含两个整数a和b,表示点a和点b之间存在一条边。
输出格式
输出一个整数m,表示重心的所有的子树中最大的子树的结点数目。
数据范围
1≤n≤1051≤n≤105
输入样例
9
1 2
1 7
1 4
2 8
2 5
4 3
3 9
4 6
输出样例:
4
import java.util.Scanner;
public class Code_0708_TreeBfs {
//树的重心!
static int n;
static int N = 100010;
static int M = N * 2;
//h是代表头节点
static int[] h = new int[N];
//存储的值
static int[] e = new int[M];
//下一个的索引
static int[] ne = new int[M];
static int idx;
//只遍历一次
static boolean[] st = new boolean[N];
//init
static int ans = Integer.MAX_VALUE;
//树和图都是这么做的!
//将b插到a的后面
static void add(int a , int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
// static void dfs(int u ){
// st[u] = true;
//
// for (int i = h[u];i != -1;i = ne[i]){
// int j = e[i];
// if (!st[j]){
// dfs(j);
// }
// }
// }
// 以u为根的子树中,点的数量
static int dfs(int u ){
st[u] = true;
int sum = 1, res = 0;
for (int i = h[u];i != -1;i = ne[i]){
int j = e[i];
if (!st[j]){
int s = dfs(j);
res = Math.max(res,s);
sum += s;
}
}
res = Math.max(res,n - sum);
ans = Math.min(ans,res);
return sum;
}
public static void main(String[] agrs){
//把里面的值都赋值成-1
//init
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int x : h){
x = - 1;
}
for (int i = 0;i < n - 1;i++){
int a, b;
a = sc.nextInt();
b = sc.nextInt();
add(a,b);
add(b,a);
}
dfs(1);
System.out.println(ans);
}
}