Skip to content

Commit 6f9084c

Browse files
authored
Create Prim's_algorithm.py
### Prim’s Algorithm - **Language:** C++ - **Description:** Constructs a Minimum Spanning Tree (MST) by starting with one vertex and repeatedly adding the smallest possible edge connecting a vertex inside the MST to one outside it. - **Complexity:** O(E log V) - **Use Case:** Network design, cost minimization
1 parent 788d95b commit 6f9084c

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

greedy_methods/Prim's_algorithm.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Prim's Algorithm - Minimum Spanning Tree (MST)
2+
// Language: C++
3+
// Category: Greedy Algorithms
4+
5+
#include <iostream>
6+
#include <vector>
7+
#include <queue>
8+
#include <utility>
9+
10+
using namespace std;
11+
12+
void primMST(int V, vector<vector<pair<int, int>>> &adj) {
13+
vector<int> key(V, INT_MAX);
14+
vector<int> parent(V, -1);
15+
vector<bool> inMST(V, false);
16+
17+
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
18+
19+
// Start from vertex 0
20+
key[0] = 0;
21+
pq.push({0, 0});
22+
23+
while (!pq.empty()) {
24+
int u = pq.top().second;
25+
pq.pop();
26+
27+
inMST[u] = true;
28+
29+
for (auto &[v, weight] : adj[u]) {
30+
if (!inMST[v] && weight < key[v]) {
31+
key[v] = weight;
32+
pq.push({key[v], v});
33+
parent[v] = u;
34+
}
35+
}
36+
}
37+
38+
cout << "Edges in MST:\n";
39+
int totalWeight = 0;
40+
for (int i = 1; i < V; ++i) {
41+
cout << parent[i] << " - " << i << " (" << key[i] << ")\n";
42+
totalWeight += key[i];
43+
}
44+
cout << "Total Weight = " << totalWeight << endl;
45+
}
46+
47+
int main() {
48+
int V, E;
49+
cout << "Enter number of vertices and edges: ";
50+
cin >> V >> E;
51+
52+
vector<vector<pair<int, int>>> adj(V);
53+
cout << "Enter edges (u v w):\n";
54+
for (int i = 0; i < E; ++i) {
55+
int u, v, w;
56+
cin >> u >> v >> w;
57+
adj[u].push_back({v, w});
58+
adj[v].push_back({u, w});
59+
}
60+
61+
primMST(V, adj);
62+
63+
return 0;
64+
}

0 commit comments

Comments
 (0)