并查集理论基础
并查集理论基础很重要,明确并查集解决什么问题,代码如何写,对后面做并查集类题目很有帮助。
寻找存在的路径
并查集裸题,学会理论基础后,本题直接可以直接刷过
import java.util.Scanner;
import java.util.Vector;
public class Main {
private static int n;
private static Vector<Integer> father = new Vector<>(101, 0);
private static void init() {
for (int i = 1; i <= n; i++) father.set(i, i);
}
private static int find(int u) {
if (u == father.get(u)) return u;
return father.set(u, find(father.get(u)));
}
private static boolean isSame(int u, int v) {
u = find(u);
v = find(v);
return u == v;
}
private static void join(int u, int v) {
u = find(u);
v = find(v);
if (u == v) return;
father.set(v, u);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
int m = scanner.nextInt();
init();
while (m-- > 0) {
int s = scanner.nextInt();
int t = scanner.nextInt();
join(s, t);
}
int source = scanner.nextInt();
int destination = scanner.nextInt();
if (isSame(source, destination)) System.out.println(1);
else System.out.println(0);
}
}