图论---图的遍历 树的重心 数组模拟邻接表 dfs java
Published on 2022-11-17 23:03 in 暂未分类 with 林动

图论---图的遍历 树的重心 数组模拟邻接表 dfs java

    题目链接:https://www.acwing.com/problem/content/description/848/

    给定一颗树,树中包含 n 个结点(编号 1∼n)和 n−1 条无向边。

    请你找到树的重心,并输出将重心删除后,剩余各个连通块中点数的最大值。

    重心定义:重心是指树中的一个结点,如果将这个点删除后,剩余各个连通块中点数的最大值最小,那么这个节点被称为树的重心。

    输入格式
    第一行包含整数 n,表示树的结点数。

    接下来 n−1 行,每行包含两个整数 a 和 b,表示点 a 和点 b 之间存在一条边。

    输出格式
    输出一个整数 m,表示将重心删除后,剩余各个连通块中点数的最大值。

    数据范围
    1≤n≤105

    import java.util.*;
    
    public class Main
    {
    	static int n,N=100005,M=200005,s,ans=N;
    	static int h[]=new int [N],e[]=new int [M],ne[]=new int[M],idx,dist[]=new int [N];
    	static boolean st[]=new boolean [M];
    	static void add(int a,int b)
    	{
    		e[idx]=b;ne[idx]=h[a];h[a]=idx++;
    	}
    	static int dfs(int u)
    	{
    		int sum=1,t=0,res=0;
    		for(int i=h[u];i!=-1;i=ne[i])
    		{
    			int j=e[i];
    			if(!st[j])
    			{
    				st[j]=true;
    				t=dfs(j);
    				sum+=t;
    				res=Math.max(t, res);
    			}
    		}
    		res=Math.max(res, n-sum);
    		ans=Math.min(res, ans);
    		return sum;
    	}
    	public static void main(String args[])
    	{
    		Scanner sc=new Scanner(System.in);
    		n=sc.nextInt();
    		Arrays.setAll(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);
    	}
    }
    
    posted @   林动  阅读(13)  评论(0编辑  收藏  举报
    相关博文:
    阅读排行:
    · 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
    · 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
    · 【自荐】一款简洁、开源的在线白板工具 Drawnix
    · 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
    · Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
    点击右上角即可分享
    微信分享提示