Skip to content

Commit 6948877

Browse files
authored
Create 1579. Remove Max Number of Edges to Keep Graph Fully Traversable1 (#517)
2 parents a552a41 + 5f97e33 commit 6948877

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
class DisjointSetUnion {
4+
vector<int> parent;
5+
vector<int> rank;
6+
7+
public:
8+
DisjointSetUnion(int n) {
9+
parent.resize(n);
10+
rank.resize(n, 0);
11+
for (int i = 0; i < n; ++i) {
12+
parent[i] = i;
13+
}
14+
}
15+
16+
int find(int u) {
17+
if (parent[u] != u) {
18+
parent[u] = find(parent[u]); // Path compression
19+
}
20+
return parent[u];
21+
}
22+
23+
void unionByRank(int u, int v) {
24+
int rootU = find(u);
25+
int rootV = find(v);
26+
if (rootU != rootV) {
27+
if (rank[rootU] > rank[rootV]) {
28+
parent[rootV] = rootU;
29+
} else if (rank[rootU] < rank[rootV]) {
30+
parent[rootU] = rootV;
31+
} else {
32+
parent[rootV] = rootU;
33+
rank[rootU]++;
34+
}
35+
}
36+
}
37+
};
38+
39+
class Solution {
40+
public:
41+
int maxNumEdgesToRemove(int n, vector<vector<int>>& e) {
42+
DisjointSetUnion a(n+1);
43+
DisjointSetUnion b(n+1);
44+
int ans=0;
45+
for(auto it:e) {
46+
if(it[0]==3){
47+
if(a.find(it[1])==a.find(it[2])){ans++; continue; }
48+
a.unionByRank(it[1],it[2]);
49+
b.unionByRank(it[1],it[2]);
50+
}
51+
}
52+
for(auto it:e) {
53+
if(it[0]!=3){
54+
if(it[0]==1){
55+
if(a.find(it[1])==a.find(it[2])){ans++; continue; }
56+
a.unionByRank(it[1],it[2]);
57+
} else {
58+
if(b.find(it[1])==b.find(it[2])){ans++; continue; }
59+
b.unionByRank(it[1],it[2]);
60+
}
61+
}
62+
}
63+
int k=a.find(1);
64+
for(int i=1;i<=n;i++){
65+
if(k!=a.find(i) or k!=b.find(i)){
66+
return -1;
67+
}
68+
}
69+
return ans;
70+
}
71+
};

0 commit comments

Comments
 (0)