连通网络
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
Code
import java.util.*;
public class Main {
static int[] pre;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- != 0) {
int n = sc.nextInt();
int m = sc.nextInt();
pre = new int[n + 1];
for (int i = 1; i <= n; i++) {
pre[i] = i;
}
while (m-- != 0) {
int x = sc.nextInt();
int y = sc.nextInt();
join(x, y);
}
int cnt = n - 1;
for (int i = 1; i <= n; i++) {
if (pre[i] != i) {
cnt--;
}
}
System.out.println(cnt);
}
sc.close();
}
public static int find(int x) {
if (pre[x] == x)
return x;
return pre[x] = find(pre[x]);
}
public static void join(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
pre[a] = b;
}
}
}
反思:
Java的基础练习……为什么语法基础练习里会有一道并查集啊∑ ( °△ °|||)!注意基站序号从1开始。初始cnt为全连通状态下的道路数量,遍历pre,只要有不连通的就减少。