-
Notifications
You must be signed in to change notification settings - Fork 0
/
kruskal_MST.txt
105 lines (85 loc) · 2.05 KB
/
kruskal_MST.txt
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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> parent;
vector<int> ranks;
int graph[6][3] = {{0,2,4},{0,1,3},{1,3,2},{1,5,1},{3,4,6},{2,4,5}};
void init_rank()
{
parent.resize(10);
ranks.resize(10);
for (int i = 0; i < 10; i++) {
parent[i] = i;
ranks[i] = 0;
}
}
int find_parent(int x)
{
if (parent[x] != x)
parent[x] = find_parent(parent[x]);
return parent[x];
}
void union_nodes(int x, int y)
{
int xroot = find_parent(x);
int yroot = find_parent(y);
if (xroot != yroot) {
if (ranks[xroot] > ranks[yroot]) {
parent[yroot] = xroot;
} else if (ranks[xroot] < ranks[yroot]) {
parent[xroot] = yroot;
} else {
parent[xroot] = yroot;
}
}
}
struct edge {
int u;
int v;
int w;
bool operator<(edge &e) {
return w < e.w;
}
};
bool f(vector<int> &first, vector<int> &second)
{
return first[2] < second[2];
}
int main()
{
vector<vector<int>> edges(6);
init_rank();
for (int i = 0; i < 6; i++) {
edges[i].push_back(graph[i][0]);
edges[i].push_back(graph[i][1]);
edges[i].push_back(graph[i][2]);
}
sort(edges.begin(), edges.end(), f);
cout << "sorting done" << endl;
for (int i = 0; i < 6; i++) {
for (int x : edges[i]) {
cout << x << " ";
}
cout << endl;
}
vector<struct edge> mst;
for (int i = 0; i < 6; i++) {
vector<int> temp_edge = edges[i];
if (find_parent(temp_edge[0]) != find_parent(temp_edge[1])) {
union_nodes(temp_edge[0], temp_edge[1]);
struct edge temp;
temp.u = temp_edge[0];
temp.v = temp_edge[1];
temp.w = temp_edge[2];
mst.push_back(temp);
}
}
cout << "MST - " << endl;
while(!mst.empty()) {
struct edge temp = mst.back();
mst.pop_back();
cout << "edge - " << temp.u << " " << temp.v << " " << temp.w << endl;
}
return 0;
}