-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskal-algorithm.cpp
More file actions
112 lines (97 loc) · 2.1 KB
/
Copy pathkruskal-algorithm.cpp
File metadata and controls
112 lines (97 loc) · 2.1 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<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef struct Edge {
int a;
int b;
int w;
} Edge;
bool compareByWeight(Edge a, Edge b)
{
return a.w < b.w;
}
void Union(vector<int>& a, vector<int>& b)
{
a.insert(a.end(), b.begin(), b.end());
b[0] = a[0];
}
bool Find(int a, int b, vector<vector<int> > allSets)
{
int i, j;
bool find;
for(i=0; i<allSets.size(); i++)
{
find = false;
for(j=0; j<allSets[i].size(); j++)
{
if((allSets[i][j] == a)||(allSets[i][j] == b))
{
if(!find) find = true;
else return true;
}
}
}
return false;
}
vector<Edge> Kruskal(vector<Edge> edges, int v)
{
vector<Edge> MST;
int i, vInMST = 1, a, b;
vector<vector<int> > allSets;
vector<int> newSet;
/* Make sets for all vertices */
for(i=0; i<v; i++)
{
allSets.push_back(newSet);
allSets[i].push_back(i);
}
/* Going through the edges */
i = 0;
while((vInMST < v)&&(i < edges.size()-1))
{
a = edges[i].a;
b = edges[i].b;
if(!Find(a, b, allSets))
{
MST.emplace_back(edges[i]);
Union(allSets[a], allSets[b]);
vInMST++;
}
i++;
}
if(vInMST < v) MST[0].a = -1;
return MST;
}
int main()
{
int v, e, i, a, b, w;
Edge edge;
vector<Edge> edges, result;
/* Input */
cout << "Number of vertices:";
cin >> v;
cout << "Number of edges:";
cin >> e;
for(i=0; i<e; i++)
{
cin >> a >> b >> w;
edge.a = a;
edge.b = b;
edge.w = w;
edges.push_back(edge);
}
sort(edges.begin(), edges.end(), compareByWeight);
result = Kruskal(edges, v);
/* Output */
if(result[0].a != -1)
{
cout << "Minimal Spanning Tree include edges:" << endl;
for(i=0; i<result.size(); i++)
{
cout << result[i].a << " - " << result[i].b << endl;
}
}
else cout << "Minimal Spanning Tree does not exists";
return 0;
}