From 34c84edc87826197631afe42c00e38c4b4d20bc8 Mon Sep 17 00:00:00 2001 From: Laiba Ashfaq Date: Sun, 12 Oct 2025 23:26:42 +0500 Subject: [PATCH] Implement Prim's algorithm for minimum spanning tree MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Algorithm Name: Prim’s Algorithm Language: C++ Category: Greedy Algorithms (though you mentioned “Stacks & Queues” in the form, it’s actually a graph/greedy algorithm) Difficulty: Beginner-friendly / Medium Description: Builds a Minimum Spanning Tree (MST) by always adding the cheapest edge connecting the tree to an unconnected vertex. --- CPP/graph/PrimAlgo.cpp | 49 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 CPP/graph/PrimAlgo.cpp diff --git a/CPP/graph/PrimAlgo.cpp b/CPP/graph/PrimAlgo.cpp new file mode 100644 index 0000000..bcb3d27 --- /dev/null +++ b/CPP/graph/PrimAlgo.cpp @@ -0,0 +1,49 @@ +#include +using namespace std; + +const int INF = 1e9; + +void primMST(vector>> &adj, int V) { + vector key(V, INF); + vector parent(V, -1); + vector inMST(V, false); + + key[0] = 0; + + for (int count = 0; count < V-1; count++) { + int u = -1; + for (int i = 0; i < V; i++) + if (!inMST[i] && (u == -1 || key[i] < key[u])) + u = i; + + inMST[u] = true; + + for (auto &edge : adj[u]) { + int v = edge.first; + int w = edge.second; + if (!inMST[v] && w < key[v]) { + key[v] = w; + parent[v] = u; + } + } + } + + cout << "Edge \tWeight\n"; + for (int i = 1; i < V; i++) + cout << parent[i] << " - " << i << " \t" << key[i] << "\n"; +} + +int main() { + int V, E; + cin >> V >> E; + vector>> adj(V); + 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(adj, V); + return 0; +}