-
Notifications
You must be signed in to change notification settings - Fork 138
/
Solution.cpp
84 lines (73 loc) · 1.8 KB
/
Solution.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
class DisjointSets {
public:
DisjointSets(int n) {
for (int i = 0; i < n; i++) {
makeSet(i);
}
}
int findSet(int node) {
if (parent[node] == node) { return node; }
parent[node] = findSet(parent[node]);
return parent[node];
}
int unionSets(int firstNode, int secondNode) {
int firstNodeParent = findSet(firstNode);
int secondNodeParent = findSet(secondNode);
if (firstNodeParent == secondNodeParent) {
return firstNodeParent;
}
if (rank[firstNodeParent] > rank[secondNodeParent]) {
parent[secondNodeParent] = firstNodeParent;
size[firstNodeParent] += size[secondNodeParent];
return firstNodeParent;
}
parent[firstNodeParent] = secondNodeParent;
size[secondNodeParent] += size[firstNodeParent];
if (rank[firstNodeParent] == rank[secondNodeParent]) {
rank[secondNodeParent] += 1;
}
return secondNodeParent;
}
int getSize(int node) {
return size[findSet(node)];
}
private:
unordered_map<int, int> parent;
unordered_map<int, int> size;
unordered_map<int, int> rank;
void makeSet(int elem) {
parent[elem] = elem;
size[elem] = 1;
rank[elem] = 0;
}
};
int main() {
int n;
cin >> n;
int q;
cin >> q;
DisjointSets sets(n + 1);
for (int i = 0; i < q; i++) {
char tmp;
cin >> tmp;
if (tmp == 'Q') {
int node;
cin >> node;
cout << sets.getSize(node) << "\n";
} else {
int nodeFirst;
int nodeSecond;
cin >> nodeFirst;
cin >> nodeSecond;
sets.unionSets(nodeFirst, nodeSecond);
}
}
return 0;
}