树与图的存储--树的重心

给定一颗树,树中包含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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值