forked from MountAim/Graph-Coding-Minutes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path33-Find Critical and Pseudo-Critical Edges in MST.cpp
123 lines (96 loc) · 2.41 KB
/
33-Find Critical and Pseudo-Critical Edges in MST.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include<bits/stdc++.h>
using namespace std;
// DSU
vector<int> par, size;
void init(int n)
{
for(int i=0; i<n; i++)
{
par[i] = -1;
size[i] = 1;
}
}
int Find(int a)
{
if(par[a] == -1)
return a;
return par[a] = Find(par[a]);
}
void Union(int a, int b)
{
int p1 = Find(a), p2 = Find(b);
if(p1==p2)
return;
if(size[p1] < size[p2])
{
par[p1] = p2;
size[p2] += size[p1];
}
else
{
par[p2] = p1;
size[p1] = p2;
}
}
// Finding MST Cost
int MST(vector<vector<int>> edges, int avoid)
{
int cost = 0;
for(auto e: edges)
{
int id = e[3];
if(id == avoid)
continue;
int p1 = Find(e[0]);
int p2 = Find(e[1]);
if(p1 == p2)
continue;
Union(p1, p2);
cost += e[2];
}
return cost;
}
// Sort according to weight
bool cmp(vector<int> a, vector<int> b)
{
return a[2]<b[2];
}
// Driver function
vector<vector<int>> findCriticalAndPseudoCriticalEdges(int n, vector<vector<int>> edges)
{
par.resize(n);
size.resize(n);
vector<int> critical, pseudo;
for(int i=0; i<edges.size(); i++)
{
edges[i].push_back(i);
}
sort(edges.begin(), edges.end(), cmp);
init(n);
int minCost = MST(edges, -1);
for(auto e: edges)
{
init(n);
int cost = MST(edges, e[3]);
// If the cost of MST by avoiding this edge is greater or the graph is disconnected at the end point vertices of this edge, then this edge is critical
if(cost>minCost or Find(e[0])!=Find(e[1]))
{
critical.push_back(e[3]);
continue;
}
// Else check if including the edge results in BST, then it is pseudo-critical else not useful edge
init(n);
// Include this edge forcefully
Union(e[0], e[1]);
cost = e[2];
cost += MST(edges, e[3]);
if(cost == minCost)
pseudo.push_back(e[3]);
}
vector<vector<int>> ans;
sort(critical.begin(),critical.end());
sort(pseudo.begin(),pseudo.end());
ans.push_back(critical);
ans.push_back(pseudo);
return ans;
}