蓝桥杯【历届试题 合根植物】 java版

使用了并查集,不熟悉并查集的可以看一下该博主的文章,讲解通俗易懂 https://www.cnblogs.com/xzxl/p/7226557.html

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * 合根植物 (并查集)
 * @author Sylvia
 * 2019年3月4日
 */
public class Main{
	
	static int[] pre;
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int m = sc.nextInt();
		int n = sc.nextInt();
		int k = sc.nextInt();
		/*long startTime = System.currentTimeMillis();*/
		pre = new int[m * n + 1];
		
		//初始化
		for(int i = 1; i <= m * n; i++) {
			pre[i] = i;
		}
		
		for(int i = 0; i < k; i++) {
			int a = sc.nextInt();
			int b = sc.nextInt();
			union(a, b);
		}
		sc.close();
		
		Set<Integer> set = new HashSet<Integer>();
		for(int i = 1; i <= m * n; i++) {
			set.add(find(i));
		}
		System.out.println(set.size());
		/*long endTime = System.currentTimeMillis();
		System.out.println("程序运行时间:" + (endTime - startTime) + " ms");*/
	}
	
	public static int find(int x) {
		int a = x;
		
		//寻找根结点
		while(pre[a] != a) {
			a = pre[a];
		}
		
		//缩短路径
		int b = x;
		while(pre[b] != a) {
			int temp = pre[b];
			pre[b] = a;
			b = temp;
		}
		return a;
	}
	
	public static void union(int x, int y) {
		int px = find(x);
		int py = find(y);
		if(px != py) {
            //合并分支
			pre[px] = py;
		}
	}
	
}

猜你喜欢

转载自blog.csdn.net/Sylvia_17/article/details/88214031