-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskal.cpp
More file actions
95 lines (84 loc) · 2.46 KB
/
Kruskal.cpp
File metadata and controls
95 lines (84 loc) · 2.46 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
#include <iostream>
#include <vector>
using namespace std;
struct Edge {
int src, dest, weight;
};
struct Subset {
int parent, rank;
};
class Graph {
int V;
vector<Edge> edges;
public:
Graph(int V) {
this->V = V;
}
void addEdge(int src, int dest, int weight) {
Edge edge = {src, dest, weight};
edges.push_back(edge);
}
int find(vector<Subset>& subsets, int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
void Union(vector<Subset>& subsets, int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
void sortEdgesByWeight() {
int n = edges.size();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (edges[j].weight > edges[j + 1].weight) {
Edge temp = edges[j];
edges[j] = edges[j + 1];
edges[j + 1] = temp;
}
}
}
}
void KruskalMST() {
vector<Edge> result;
int e = 0;
int i = 0;
sortEdgesByWeight();
vector<Subset> subsets(V);
for (int v = 0; v < V; v++) {
subsets[v].parent = v;
subsets[v].rank = 0;
}
while (e < V - 1 && i < edges.size()) {
Edge next_edge = edges[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
result.push_back(next_edge);
Union(subsets, x, y);
e++;
}
}
cout << "Edge \tWeight\n";
for (i = 0; i < result.size(); i++)
cout << result[i].src << " - " << result[i].dest << " \t" << result[i].weight << endl;
}
};
int main() {
int V = 4;
Graph graph(V);
graph.addEdge(0, 1, 10);
graph.addEdge(0, 2, 6);
graph.addEdge(0, 3, 5);
graph.addEdge(1, 3, 15);
graph.addEdge(2, 3, 4);
graph.KruskalMST();
}