题目描述
给定一颗树,树中包含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
如图所示,删除1,剩余的3个子树的数量最大为4, 如果删除2,剩余3个子树的数量中6,按照题意,去最大的最小,即4
java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main{
static int N = 100010, M = N * 2; // 无向边
static int[] h = new int[N], e = new int[M], ne = new int[M];
static int idx;
static int n; // 数目
static boolean st[] = new boolean[N];
static int ans = N; // 最终结果值
// 构造邻接矩阵
private static void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
private 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) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int i = 0; i < N; i++) {
h[i] = -1;
}
for (int i = 0; i < n - 1; i++) { // 树 n-1条边
int a = sc.nextInt();
int b = sc.nextInt();
add(a, b);
add(b, a);
}
dfs(1);
System.out.println(ans);
}
}
python
N = 100010
M = 2 * N
h = [-1] * N
e = [0] * M
ne = [0] * M
idx = 0
n = 0
ans = N
st = [False] * N
def add(a, b):
global idx
e[idx] = b
ne[idx] = h[a]
h[a] = idx
idx += 1
def dfs(u):
global idx, n, ans
st[u] = True
sum, res = 1, 0
i = h[u]
while (i != -1):
j = e[i]
if (not st[j]):
s = dfs(j)
res = max(res, s)
sum += s
i = ne[i]
res = max(res, n - sum)
ans = min(ans, res)
return sum
def main():
global n, ans
n = int(input())
for i in range(n - 1):
a, b = map(int, input().split())
add(a, b)
add(b, a)
dfs(1)
print(ans)
if __name__ == '__main__':
main()
c++
#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;
bool st[N];
int ans = N;
//构造邻接矩阵
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
//dfs实现的功能: 以u为根的子树中点的数量
int dfs(int u){
//标记该点已经被搜过,下次不需要继续搜素该点的情况
//因为不涉及到回溯,只是单纯的遍历所有节点,不需要对现场的恢复。
st[u] = true;
int sum = 1, res = 0; //sum用来统计当前节点下的所有子树数量,设置为1是因为当前节点u本身数量为1 res用于统计子树,同时考虑叶子节点(ne[u] = -1)下子树为0
for(int i = h[u]; i != -1; i = ne[i]){
int j = e[i];
if(!st[j]){
int s = dfs(j); //当前根节点u下不同子树的数量
res = max(res, s); //子树中最大的数量
sum += s; //以u为根的子树的数量
}
}
res = max(res, n - sum); //n - sum除了u为根的子树的数量以外的子树数量
ans = min(ans, res); //记录不同根节点u下最大子树数量的最小值
return sum;
}
int main(){
cin >> n;
memset(h, -1, sizeof h);
for(int i = 0; i < n - 1; i ++){
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
dfs(1);
cout << ans << endl;
return 0;
}
👍🏻