-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKrush.cpp
More file actions
98 lines (90 loc) · 1.75 KB
/
Krush.cpp
File metadata and controls
98 lines (90 loc) · 1.75 KB
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
#include<bits/stdc++.h>
using namespace std;
class edge{
public:
int s,d,w;
Edge(int ss,int dd,int ww)
{
s = ss;
d = dd;
w = ww;
}
};
bool compare(edge a,edge b)
{
return a.w<b.w;
}
edge obj[100];
edge MST[100];
edge bad[100];
int parent[100];
int Find_Set(int r)
{
return (parent[r]==r) ? r : Find_Set(parent[r]);
}
void Kruskal(int ed,int ver)
{
for(int i=1;i<=ver;i++)
{
parent[i] = i;
}
int cnt=0,l=0,m=0;
for(int i=0;i<ed;i++)
{
int u,v,j,k;
u = obj[i].s;
v = obj[i].d;
j = Find_Set(u);
k = Find_Set(v);
if(j!=k && cnt<ver-1) //
{
MST[l] = obj[i];
cnt++;
l++;
parent[u]=v;
}
// else
// {
// bad[m] = obj[i];
// m++;
// }
}
int total_cost = 0;
for(int i=0;i<l;i++)
{
cout<<MST[i].s<<" ";
cout<<MST[i].d<<" ";
cout<<MST[i].w<<endl;
total_cost +=MST[i].w;
}
cout<<"Total Minimum Cost = "<<total_cost<<endl;
/// baad array print
// for(int i=0;i<m;i++)
// {
// cout<<bad[i].s<<" ";
// cout<<bad[i].d<<" ";
// cout<<bad[i].w<<endl;
// }
}
int main()
{
freopen("in.txt","r",stdin);
int ed,ver;
cin>>ver>>ed;
for(int i=0;i<ed;i++)
{
int u,v,cost;
cin>>u>>v>>cost;
obj[i].Edge(u,v,cost);
}
sort(obj,obj+ed,compare);
for(int i=0;i<ed;i++)
{
cout<<obj[i].s<<" ";
cout<<obj[i].d<<" ";
cout<<obj[i].w<<endl;
}
cout<<"MST Display"<<endl;
Kruskal(ed,ver);
return 0;
}