forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-max-number-of-edges-to-keep-graph-fully-traversable.cpp
67 lines (61 loc) · 1.8 KB
/
remove-max-number-of-edges-to-keep-graph-fully-traversable.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
// Time: O(n + m * α(n)) ~= O(n + m)
// Space: O(n)
class Solution {
public:
int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) {
int result = 0;
UnionFind union_find_a(n), union_find_b(n);
for (const auto& edge : edges) {
int t = edge[0], i = edge[1], j = edge[2];
if (t != 3) {
continue;
}
bool a = union_find_a.union_set(i - 1, j - 1);
bool b = union_find_b.union_set(i - 1, j - 1);
if (!a && !b) {
++result;
}
}
for (const auto& edge : edges) {
int t = edge[0], i = edge[1], j = edge[2];
if (t == 1) {
if (!union_find_a.union_set(i - 1, j - 1)) {
++result;
}
} else if (t == 2) {
if (!union_find_b.union_set(i - 1, j - 1)) {
++result;
}
}
}
return union_find_a.size() == 1 && union_find_b.size() == 1 ? result : -1;
}
private:
class UnionFind {
public:
UnionFind(const int n) : set_(n), size_(n) {
iota(set_.begin(), set_.end(), 0);
}
int find_set(const int x) {
if (set_[x] != x) {
set_[x] = find_set(set_[x]); // Path compression.
}
return set_[x];
}
bool union_set(const int x, const int y) {
int x_root = find_set(x), y_root = find_set(y);
if (x_root == y_root) {
return false;
}
set_[max(x_root, y_root)] = min(x_root, y_root);
--size_;
return true;
}
int size() const {
return size_;
}
private:
vector<int> set_;
int size_;
};
};