-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlgoTaskNo2.cpp
77 lines (62 loc) · 1.87 KB
/
AlgoTaskNo2.cpp
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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Edge {
int source, destination, weight;
};
bool compareEdges(Edge one, Edge two) {
return one.weight < two.weight;
}
int find(vector<int>& parent, int x) {
if (parent[x] != x) {
parent[x] = find(parent, parent[x]);
}
return parent[x];
}
void unionSets(vector<int>& parent, vector<int>& rank, int x, int y) {
int rootX = find(parent, x);
int rootY = find(parent, y);
if (rootX != rootY) {
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
vector<Edge> kruskalMST(int V, vector<Edge>& edges) {
sort(edges.begin(), edges.end(), compareEdges);
vector<int> parent(V), rank(V, 0);
for (int i = 0; i < V; ++i) parent[i] = i;
vector<Edge> mst;
for (const Edge& edge : edges) {
if (find(parent, edge.source) != find(parent, edge.destination)) {
mst.push_back(edge);
unionSets(parent, rank, edge.source, edge.destination);
}
}
return mst;
}
int main() {
int V, E;
cout << "Enter the no. vertices and edges: ";
cin >> V >> E;
vector<Edge> edges(E);
cout << "Enter the edges (src, dest, weight):\n";
for (int i = 0; i < E; ++i) {
cin >> edges[i].source >> edges[i].destination >> edges[i].weight;
}
vector<Edge> mst = kruskalMST(V, edges);
cout << "The Edges in the Minimum Spanning Tree:\n";
int totalWeight = 0;
for (const Edge& edge : mst) {
cout << edge.source << " -- " << edge.destination << " == " << edge.weight << "\n";
totalWeight += edge.weight;
}
cout << "The total weight of the MST: " << totalWeight << "\n";
return 0;
}