From 17b8deec06b2e454d557366b3d479649b528e59b Mon Sep 17 00:00:00 2001 From: Himanshu Airan <62210670+Himanshu-77@users.noreply.github.com> Date: Thu, 21 May 2020 20:55:53 +0530 Subject: [PATCH] Create Prim.cpp (#750) * Create Prim.cpp Created file for Prim's Algorithm in graph that was still missing. * Update Prim.cpp Edited indentation part * Update Prim.cpp indentation updated * Update Prim.cpp Indentation updated * Rename Prim.cpp to prim.cpp Co-authored-by: Christian Clauss --- graph/prim.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 graph/prim.cpp diff --git a/graph/prim.cpp b/graph/prim.cpp new file mode 100644 index 000000000..2923b5b25 --- /dev/null +++ b/graph/prim.cpp @@ -0,0 +1,58 @@ +// C++ program to implement Prim's Algorithm +#include +#include +#include + +const int MAX = 1e4 + 5; +typedef std:: pair PII; + +bool marked[MAX]; +std:: vector adj[MAX]; + +int prim(int x) { + // priority queue to maintain edges with respect to weights + std:: priority_queue, std:: greater > Q; + int y; + int minimumCost = 0; + PII p; + + Q.push(std:: make_pair(0, x)); + while (!Q.empty()) { + // Select the edge with minimum weight + p = Q.top(); + Q.pop(); + x = p.second; + // Checking for cycle + if (marked[x] == true) + continue; + minimumCost += p.first; + marked[x] = true; + for (int i = 0; i < adj[x].size(); ++i) { + y = adj[x][i].second; + if (marked[y] == false) + Q.push(adj[x][i]); + } + } + return minimumCost; +} + +int main() { + int nodes, edges, x, y; + int weight, minimumCost; + + std:: cin >> nodes >> edges; // number of nodes & edges in graph + if (nodes == 0 || edges == 0) + return 0; + + // Edges with their nodes & weight + for (int i = 0; i < edges; ++i) { + std::cin >> x >> y >> weight; + adj[x].push_back(std:: make_pair(weight, y)); + adj[y].push_back(std:: make_pair(weight, x)); + } + + // Selecting 1 as the starting node + minimumCost = prim(1); + std:: cout << minimumCost << std:: endl; + return 0; +}