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

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);
		}
	}
}

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

发布了27 篇原创文章 · 获赞 2 · 访问量 932

猜你喜欢

转载自blog.csdn.net/wcy8733996wcy/article/details/104426120
今日推荐