-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerging-communities.cpp
68 lines (57 loc) · 1.33 KB
/
merging-communities.cpp
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
63
64
65
66
67
68
#include <iostream>
#include <vector>
using namespace std;
class DisjointSet {
public:
DisjointSet(int n) {
parent.resize(n + 1);
size.resize(n + 1);
for (int i = 1; i <= n; ++i) {
parent[i] = i;
size[i] = 1;
}
}
int find(int x) {
if (x != parent[x]) {
parent[x] = find(parent[x]); // Path compression
}
return parent[x];
}
void union_sets(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
if (size[rootX] < size[rootY]) {
swap(rootX, rootY);
}
parent[rootY] = rootX;
size[rootX] += size[rootY];
}
}
int get_size(int x) {
int rootX = find(x);
return size[rootX];
}
private:
vector<int> parent;
vector<int> size;
};
int main() {
int n, q;
cin >> n >> q;
DisjointSet ds(n);
for (int i = 0; i < q; ++i) {
char queryType;
cin >> queryType;
if (queryType == 'M') {
int u, v;
cin >> u >> v;
ds.union_sets(u, v);
} else if (queryType == 'Q') {
int u;
cin >> u;
cout << ds.get_size(u) << endl;
}
}
return 0;
}