AcWing-846 树的重心(java实现)

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);
	}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杜柠函

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值