文章

2

粉丝

33

获赞

0

访问

803

头像
并查集 题解:
P1586
发布于2024年3月4日 23:18
阅读数 389

import java.util.Scanner;
public class Main{
	public static int[] list;
	public static void main(String[] args){
		int N, M, Z, X, Y;
		try(Scanner scanner = new Scanner(System.in)){
			N = scanner.nextInt();
			M = scanner.nextInt();
			list = new int[N + 1];
			while(N > 0){
				list[N] = N--;
			}
			while(M-- > 0){
				Z = scanner.nextInt();
				X = scanner.nextInt();
				Y = scanner.nextInt();
				if(Z == 2){
					System.out.println(getRoot(X) == getRoot(Y) ? "Y" : "N");
				}else if(Z == 1){
					union(X, Y);
				}
			}
		}
	}
	public static int getRoot(int num){
		while(num != list[num]){
			num = list[num];
		}
		return num;
	}
	public static void union(int a, int b){
		int aRoot = getRoot(a);
		int bRoot = getRoot(b);
		if(aRoot == bRoot){
			return;
		}
		list[aRoot] = bRoot;
	}
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发