forked from Chayandas07/LeetCode-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
81 lines (81 loc) · 2.28 KB
/
1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
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
75
76
77
78
79
80
81
class Solution {
public:
vector<int>parent;
void disjoint(int size){
parent.resize(size+1);
for(int i=0;i<=size;i++)
parent[i]=(i);
}
int find(int u){
if(parent[u]==u)return u;
return parent[u] = find(parent[u]);
}
void merge(int u,int v){
int ua = find(u);
int ub = find(v);
parent[ua] = ub;
}
int help1(vector<vector<int>>& e,int j,int n){
disjoint(n+1);
vector<pair<int,pair<int,int>>>v;
for(int i=0;i<e.size();i++){
if(i==j)continue;
v.push_back({e[i][2],{e[i][0],e[i][1]}});
}
sort(v.begin(),v.end());
int mst_weight = 0;
int edges = 0;
for(int i=0;i<v.size();i++){
auto x = v[i];
int u = find(x.second.first);
int v = find(x.second.second);
if(u!=v){
edges++;
mst_weight += x.first;
merge(u,v);
}
}
if(edges!=n-1)return INT_MAX;
return mst_weight;
}
int help2(vector<vector<int>>& e,int j,int n){
disjoint(n+1);
int mst_weight = e[j][2];
merge(e[j][1],e[j][0]);
vector<pair<int,pair<int,int>>>v;
for(int i=0;i<e.size();i++){
if(i==j)continue;
v.push_back({e[i][2],{e[i][0],e[i][1]}});
}
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++){
auto x = v[i];
int u = find(x.second.first);
int v = find(x.second.second);
if(u!=v){
mst_weight += x.first;
merge(u,v);
}
}
return mst_weight;
}
vector<vector<int>> findCriticalAndPseudoCriticalEdges(int n, vector<vector<int>>& e) {
disjoint(n+1);
int mst_weight = help1(e,-1,n);
vector<vector<int>>ans;
vector<int>v1,v2;
for(int i=0;i<e.size();i++){
int new_weight1 = help1(e,i,n);
int new_weight2 = help2(e,i,n);
if(new_weight1 > mst_weight){
v1.push_back(i);
}
else if(new_weight2 == mst_weight){
v2.push_back(i);
}
}
ans.push_back(v1);
ans.push_back(v2);
return ans;
}
};