连通网络
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();
}
}