连通网络

连通网络

Time Limit: 1000 ms  Memory Limit: 65536 KiB
Problem Description
网络由基站和基站间线路组成,基站连通表示两个基站可以通过线路互相到达。网络连通代表网络中任意两基站可以互相连通。现有一些网络,求这些网络至少增加多少线路成为连通网络。
 
Input
第一行输入一个数T代表测试数据个数(T<=20)。每个测试数据第一行2个数n,m 分别代表网络基站数和基站间线路数。基站的序号为从1到n。接下来m行两个数代表x,y 代表基站x,y间有一条线路。
(0 <= n, m <=  1000000)
Output
对于每个样例输出最少增加多少线路可以成为连通网络。每行输出一个结果。
 
Sample Input
2
3 1
1 2
3 2
1 2
2 3
Sample Output
1
0
Hint
 
Source

中国海洋大学第三届“朗讯杯”编程比赛高级组试题


import java.util.*;
public class Main 
{
	public static int find(int x ,int pre[])
	{
		int r = x;
		while(pre[r]!=r)
			r=pre[r];
		return r;
	}
	public static void join(int x,int y,int pre[])
	{
		int fx = find(x,pre);
		int fy = find(y,pre);
		if(fx!=fy)
			pre[fx] = fy;
	}
    public static void main(String[] args)
    {
       Scanner cin = new Scanner(System.in);
       int t , i , n , m ,total,j;
       int a ,b;
       int []pre = new int[10000000];
       t = cin.nextInt();
       while(t>0)
       {
    	   n = cin.nextInt();
    	   m = cin.nextInt();
    	   total = n-1;
    	   for(i = 1;i<=n;i++)
    		  pre[i] = i;
    	   for(j = 1;j<=m;j++)
    	   {
    		 a = cin.nextInt();
    		 b = cin.nextInt();
    		 join(a,b,pre);
    	   }
    	   for(i = 1;i<=n;i++)
    	   {
    		   if(pre[i]!=i)
    			   total--;
    	   }
    	   System.out.println(total);
    	   t--;
       }
       cin.close();
    }
    
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值