-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathDisjointSetUnion.java
More file actions
62 lines (51 loc) · 1.56 KB
/
DisjointSetUnion.java
File metadata and controls
62 lines (51 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.*;
public class DisjointSetUnion {
static int getParent(int x, int[] parent) {
if (parent[x] == x) return x;
parent[x] = getParent(parent[x], parent); // Path compression
return parent[x];
}
static void unite(int a, int b, int[] parent, int[] rank) {
int pa = getParent(a, parent);
int pb = getParent(b, parent);
if (pa == pb) return; // Already in the same set
if (rank[pa] > rank[pb]) {
parent[pb] = pa;
} else if (rank[pb] > rank[pa]) {
parent[pa] = pb;
} else {
rank[pa]++;
parent[pb] = pa;
}
}
static void solve(Scanner sc) {
int n = sc.nextInt();
int q = sc.nextInt();
int[] rank = new int[n];
int[] parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
for (int i = 0; i < q; i++) {
String str = sc.next();
int a = sc.nextInt();
int b = sc.nextInt();
a--; b--; // zero-based indexing
if (str.charAt(0) == 'u') {
unite(a, b, parent, rank);
} else {
if (getParent(a, parent) == getParent(b, parent)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
solve(sc);
sc.close();
}
}