import java.util.Scanner;
/**
* 并查集+路径压缩
* 解决问题:解决关联关系,
* 1、初始化所有的节点祖先节点为自己。
* 2、查找每个节点的祖先节点。路径压缩(搜索到祖先节点,并将子节点上级节点指向祖先节点)
* 3,合并:把一个点的祖先变成另一个点的祖先。
*/
public class P3367 {
static int T,n,m;
static int[] f;//元素i的祖先节点
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
T = sc.nextInt();
for(int test_case=1;test_case<=T;test_case++) {
n = sc.nextInt();
m = sc.nextInt();
f = new int[n+1];
//初始化所有的元素祖先均为自己
for(int i=1;i<=n;i++) {
f[i] = i;
}
for(int i=0;i<m;i++) {
int p1 = sc.nextInt();
int p2 = sc.nextInt();
int p3 = sc.nextInt();
if(p1==1) {
f[find(p2)]=find(p3);
}else {
if(find(p2)==find(p3)) {
System.out.println("Y");
}else {
System.out.println("N");
}
}
}
}
}
/**
* 路径压缩:返回节点K的祖先节点。
* @param k 节点
* @return k节点的祖宗节点。
*/
public static int find(int k) {
if(f[k]==k) {
return k;
}else {
return f[k] = find(f[k]);//关键:路径压缩,
}
}
}
P3367(并查集+路径压缩)
猜你喜欢
转载自blog.csdn.net/qq_28635317/article/details/111588994
今日推荐
周排行