relative
This topic is a very standard merged collection. If you don't know it, you can read this note first . I also read this study. It is best to understand it. use
Mainly divided into three parts
- Initialize, initialize everyone into a collection with only oneself,
- union, that is, to merge according to the same kind of information given by the title
- find, determine whether two people belong to the same set
The way I write below is with path compression, which can shorten the search time very well.
package cn.edu.xjtu.daily.April.day_4_11;
import java.util.Scanner;
/**
* https://www.luogu.com.cn/problem/P1551
*/
public class Main {
static int[] relation;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int p = sc.nextInt();
// 初始化
relation = new int[n];
for (int i = 0; i < n; i++) {
relation[i] = i;
}
// 根据题目所给信息合并同类
for (int i = 0; i < m; i++) {
int num1 = sc.nextInt() - 1;
int num2 = sc.nextInt() - 1;
union(num1, num2);
}
// find,查找两个人是不是属于同一个集合
for (int i = 0; i < p; i++) {
int num1 = sc.nextInt() - 1;
int num2 = sc.nextInt() - 1;
if (find(num1) == find(num2)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
sc.close();
}
/**
* 将两个节点所在集合进行合并
*
* @param x
* @param y
*/
private static void union(int x, int y) {
int xParent = find(x);
int yParent = find(y);
if (xParent > yParent) {
relation[xParent] = yParent;
} else {
relation[yParent] = xParent;
}
}
/**
* 查找给定节点所属集合
*
* @param x
* @return
*/
private static int find(int x) {
return relation[x] == x ? x : (relation[x] = find(relation[x]));
}
}