From 6b2929714133d226d0b03fa4bb99e4d057ca487e Mon Sep 17 00:00:00 2001 From: Ashish Maurya <143331001+ashishmaurya73@users.noreply.github.com> Date: Sat, 14 Sep 2024 18:11:56 +0530 Subject: [PATCH] Update 2. Prims.cpp Here i am added my own solution code of Prims algorigthm --- 01. Graphs/06. MST/2. Prims.cpp | 38 +++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/01. Graphs/06. MST/2. Prims.cpp b/01. Graphs/06. MST/2. Prims.cpp index 625517c..cf9f30a 100644 --- a/01. Graphs/06. MST/2. Prims.cpp +++ b/01. Graphs/06. MST/2. Prims.cpp @@ -49,6 +49,44 @@ int minCostConnectPoints(vector>& points) { return ans; } +// MY SOLUTION +//Function to find sum of weights of edges of the Minimum Spanning Tree. + int spanningTree(int V, vector> adj[]) + { + // code here + priority_queue, vector>, greater>>pq; + //{wt, node} + + vectorinMst(V, false); + pq.push({0, 0}); + int sum=0; + + // Total= O(E*(logE+logE))=O(ElogE) + while(!pq.empty()){ //O(E) + auto p=pq.top(); + pq.pop(); //0(log(E)) + + int wt =p.first; + int node=p.second; + if(inMst[node]==true){ + continue; + } + + inMst[node]=true; + sum+=wt; + + for(auto &it: adj[node]){ + int neighbour =it[0]; + int neighbour_wt=it[1]; + if(!inMst[neighbour] ){ + pq.push({neighbour_wt, neighbour}); //(log(E)) + } + } + + } + return sum; + } +