forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrim's_algorithm.cpp
More file actions
64 lines (51 loc) · 1.43 KB
/
Prim's_algorithm.cpp
File metadata and controls
64 lines (51 loc) · 1.43 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
// Prim's Algorithm - Minimum Spanning Tree (MST)
// Language: C++
// Category: Greedy Algorithms
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
void primMST(int V, vector<vector<pair<int, int>>> &adj) {
vector<int> key(V, INT_MAX);
vector<int> parent(V, -1);
vector<bool> inMST(V, false);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
// Start from vertex 0
key[0] = 0;
pq.push({0, 0});
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
inMST[u] = true;
for (auto &[v, weight] : adj[u]) {
if (!inMST[v] && weight < key[v]) {
key[v] = weight;
pq.push({key[v], v});
parent[v] = u;
}
}
}
cout << "Edges in MST:\n";
int totalWeight = 0;
for (int i = 1; i < V; ++i) {
cout << parent[i] << " - " << i << " (" << key[i] << ")\n";
totalWeight += key[i];
}
cout << "Total Weight = " << totalWeight << endl;
}
int main() {
int V, E;
cout << "Enter number of vertices and edges: ";
cin >> V >> E;
vector<vector<pair<int, int>>> adj(V);
cout << "Enter edges (u v w):\n";
for (int i = 0; i < E; ++i) {
int u, v, w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
primMST(V, adj);
return 0;
}