From c214e706a6291df51cd1c3f58a5258bf8f30c74c Mon Sep 17 00:00:00 2001 From: Anmol Bansal Date: Sat, 3 Oct 2020 22:24:07 +0530 Subject: [PATCH] Added Prims Algorithm for MST --- Prims_Algorithm.cpp | 72 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Prims_Algorithm.cpp diff --git a/Prims_Algorithm.cpp b/Prims_Algorithm.cpp new file mode 100644 index 0000000..5cbbe5c --- /dev/null +++ b/Prims_Algorithm.cpp @@ -0,0 +1,72 @@ +#include +#define ll long long +#define pii pair +#define fi first +#define sec second +#define pb push_back + +using namespace std; + +// Implement Prims Algorithm for MST + +ll par[1000001]; +ll ran[1000001]; + +ll find_set(ll v) { + if(v == par[v]) return v; + return par[v] = find_set(par[v]); +} + +bool union_set(ll a,ll b) { + a = find_set(a); + b = find_set(b); + + if(a!=b) { + if(ran[a]>n; + + ll e; // Number of Edges + cin>>e; + + priority_queue,vector >, greater > > edges; + for(ll i=0;i>s>>d>>w; + edges.push({w,{s,d}}); + } + + for(ll i=1;i<=n;i++) { + par[i]=i; + ran[i]=1; + } + + ll val=0; + vector > mst; + while(!edges.empty()) { + pair top = edges.top(); + edges.pop(); + + ll s = top.sec.fi,d = top.sec.sec,w = top.fi; + + if(union_set(s,d)) { + val += w; + mst.pb({w,{s,d}}); + } + } + cout<<"Value of Minimum Spanning Tree = "<"<