蓝桥杯历届试题——合根植物(并查集)

package historycontest;

import java.util.Scanner;

public class _54_DSUPlant {
	static int[] father;//必须要加static吗??
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int m=sc.nextInt();
		int n=sc.nextInt();
		int k=sc.nextInt();
		father=new int[m*n+1];
		int count=0;
		for (int i = 1; i <=m*n; i++) {
			father[i]=i;
		}
		for (int i = 1; i <=k; i++) {
			int x=sc.nextInt();
			int y=sc.nextInt();
			join(x, y);
		}
		for (int i = 1; i <=m*n; i++) {
			if (father[i]==i) {
				count++;
			}
		}
		System.out.println(count);
	}
	//查找父结点
	private static int find(int n) {
		if(father[n]==n) {
			return n;
		}else {
			father[n]=find(father[n]);
			return father[n];
		}
	}
	//连接结点
	private static void join(int a,int b) {
		if (find(a)!=find(b)) {
			father[find(a)]=find(b);
		}
	}
}

并查集相关内容可参考这篇文章,生动形象:搜索“超有爱的并查集”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值