-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskalAlgorithm.cpp
More file actions
112 lines (94 loc) · 2.06 KB
/
KruskalAlgorithm.cpp
File metadata and controls
112 lines (94 loc) · 2.06 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include<bits/stdc++.h>
#define size 100
using namespace std;
class Node
{
public:
int source;
int destination;
int weight;
Node_Edge(int s,int d,int w)
{
source = s;
destination = d;
weight = w;
}
};
Node n[size];
Node mst[size];
int p[size];
bool compare(Node u,Node v)
{
return u.weight < v.weight;
}
int Set(int parent)
{
return (p[parent]==parent) ? parent : Set(p[parent]);
}
void KruskalAlgo(int e, int v)
{
int c = 0, c1 = 0, total_weight = 0;
for(int i = 1; i <= v; i++)
{
p[i] = i;
}
for(int i = 0; i < e; i++)
{
int s,d,set_u,set_v;
s = n[i].source;
d = n[i].destination;
set_u = Set(s);
set_v = Set(d);
if(set_u != set_v && c <v-1)
{
mst[c1] = n[i];
c++;
c1++;
p[s] = d;
}
}
for(int i=0 ; i < c1; i++)
{
cout<<mst[i].source<<" ";
cout<<mst[i].destination<<" ";
cout<<mst[i].weight<<" ";
cout<<endl;
total_weight = total_weight + mst[i].weight;
}
cout<<"Total Minimum Spanning Tree Cost = "<<total_weight<<endl;
}
int main()
{
freopen("in.txt","r",stdin);
int vertex;
int edge;
int u,v,w;
cin>>vertex>>edge;
for(int i = 0; i < edge; i++)
{
cin>>u>>v>>w;
n[i].source = u;
n[i].destination = v;
n[i].weight = w;
n[i].Node_Edge(u,v,w);
}
for(int i = 0; i < edge; i++)
{
cout<<n[i].source<<" ";
cout<<n[i].destination<<" ";
cout<<n[i].weight<<" ";
cout<<endl;
}
cout<<endl<<"After Sorting :"<<endl;
sort(n,n+edge,compare);
for(int i = 0; i < edge; i++)
{
cout<<n[i].source<<" ";
cout<<n[i].destination<<" ";
cout<<n[i].weight<<" ";
cout<<endl;
}
cout<<endl<<"Minimum Spanning Tree : "<<endl;
KruskalAlgo(edge,vertex);
return 0;
}