-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
68 lines (56 loc) · 1.15 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
#include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class UnionFind {
private:
vector<int> parent;
vector<int> rank;
int components;
public:
UnionFind(int n) : parent(n), rank(n), components(n) {
for (int i = 0; i < n; ++i) {
parent[i] = i;
}
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void unite(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) {
return;
}
--components;
if (rank[rootX] < rank[rootY]) {
parent[rootX] = parent[rootY];
return;
}
parent[rootY] = parent[rootX];
if (rank[rootX] == rank[rootY]) {
++rank[rootX];
}
}
int getComponents() { return components; }
};
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
UnionFind uf(n);
for (auto const& edge : edges) {
uf.unite(edge[0], edge[1]);
}
return uf.getComponents();
}
};