SDUT - 2505 连通网络 (Java)

连通网络

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,只要有不连通的就减少。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值