-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path1579. Remove Max Number of Edges to Keep Graph Fully Traversable1
71 lines (67 loc) · 1.69 KB
/
1579. Remove Max Number of Edges to Keep Graph Fully Traversable1
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
#include <bits/stdc++.h>
using namespace std;
class DisjointSetUnion {
vector<int> parent;
vector<int> rank;
public:
DisjointSetUnion(int n) {
parent.resize(n);
rank.resize(n, 0);
for (int i = 0; i < n; ++i) {
parent[i] = i;
}
}
int find(int u) {
if (parent[u] != u) {
parent[u] = find(parent[u]); // Path compression
}
return parent[u];
}
void unionByRank(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU != rootV) {
if (rank[rootU] > rank[rootV]) {
parent[rootV] = rootU;
} else if (rank[rootU] < rank[rootV]) {
parent[rootU] = rootV;
} else {
parent[rootV] = rootU;
rank[rootU]++;
}
}
}
};
class Solution {
public:
int maxNumEdgesToRemove(int n, vector<vector<int>>& e) {
DisjointSetUnion a(n+1);
DisjointSetUnion b(n+1);
int ans=0;
for(auto it:e) {
if(it[0]==3){
if(a.find(it[1])==a.find(it[2])){ans++; continue; }
a.unionByRank(it[1],it[2]);
b.unionByRank(it[1],it[2]);
}
}
for(auto it:e) {
if(it[0]!=3){
if(it[0]==1){
if(a.find(it[1])==a.find(it[2])){ans++; continue; }
a.unionByRank(it[1],it[2]);
} else {
if(b.find(it[1])==b.find(it[2])){ans++; continue; }
b.unionByRank(it[1],it[2]);
}
}
}
int k=a.find(1);
for(int i=1;i<=n;i++){
if(k!=a.find(i) or k!=b.find(i)){
return -1;
}
}
return ans;
}
};