forked from Chayandas07/LeetCode-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1579. Remove Max Number of Edges to Keep Graph Fully Traversable
74 lines (62 loc) · 1.73 KB
/
1579. Remove Max Number of Edges to Keep Graph Fully Traversable
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
class Solution {
public:
int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) {
vector<int> rootA(n + 1);
vector<int> rootB(n + 1);
for (int i = 1; i <= n; i++) {
rootA[i] = i;
rootB[i] = i;
}
int res = 0;
int aliceEdges = 0;
int bobEdges = 0;
for (auto& edge : edges) {
if (edge[0] == 3) {
if (uni(edge[1], edge[2], rootA)) {
aliceEdges++;
if (uni(edge[1], edge[2], rootB)) {
bobEdges++;
}
} else {
res++;
}
}
}
vector<int> rootA_copy = rootA;
for (auto& edge : edges) {
if (edge[0] == 1) {
if (uni(edge[1], edge[2], rootA)) {
aliceEdges++;
} else {
res++;
}
}
}
rootA = rootA_copy;
for (auto& edge : edges) {
if (edge[0] == 2) {
if (uni(edge[1], edge[2], rootB)) {
bobEdges++;
} else {
res++;
}
}
}
return (aliceEdges == bobEdges && aliceEdges == n - 1) ? res : -1;
}
bool uni(int a, int b, vector<int>& root) {
int rootA = find(a, root);
int rootB = find(b, root);
if (rootA == rootB) {
return false;
}
root[rootA] = rootB;
return true;
}
int find(int a, vector<int>& root) {
if (root[a] != a) {
root[a] = find(root[a], root);
}
return root[a];
}
};