AcWing-846 树的重心
题目描述
给定一颗树,树中包含 n 个结点(编号 1∼n)和 n−1 条无向边。
请你找到树的重心,并输出将重心删除后,剩余各个连通块中点数的最大值。
重心定义:重心是指树中的一个结点,如果将这个点删除后,剩余各个连通块中点数的最大值最小,那么这个节点被称为树的重心。
输入格式
第一行包含整数 n,表示树的结点数。
接下来 n−1 行,每行包含两个整数 a 和 b,表示点 a 和点 b 之间存在一条边。
输出格式
输出一个整数 m,表示将重心删除后,剩余各个连通块中点数的最大值。
数据范围
1≤n≤105
输入样例
9
1 2
1 7
1 4
2 8
2 5
4 3
3 9
4 6
输出样例:
4
题解
package acWing846;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
static int N = 100010,M = N*2;
static int n;
static int h[] = new int[N],e[] = new int[M],ne[] = new int[M],idx;// h存头结点、e存储节点值、ne存储next节点值
static boolean st[] = new boolean[N];
static int ans = N;
static void add(int a,int b) {
e[idx] =b;
ne[idx]=h[a];
h[a] =idx++;
}
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[] args) throws NumberFormatException, IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
Arrays.fill(h, -1);
int n = Integer.parseInt(bf.readLine());
for(int i=0;i<n-1;i++) {
String s[] = bf.readLine().split(" ");
int a,b;
a=Integer.parseInt(s[0]);b=Integer.parseInt(s[1]);
add(a,b);add(b,a);
}
dfs(1);
System.out.println(ans);
}
}