Last active
September 20, 2017 18:32
-
-
Save lsiddiqsunny/2f376dda60f094b965ba626593dc293e to your computer and use it in GitHub Desktop.
Prim's algorithm implementation for minimum spanning tree.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
#define mx 50005 | |
typedef pair<long long int,int> PII; | |
vector<PII>g[mx]; | |
bool marked[mx]; | |
long long prim(int x) | |
{ | |
priority_queue<PII, vector<PII>, greater<PII> > Q; | |
int y; | |
long long minimumCost = 0; | |
PII p; | |
Q.push(make_pair(0, x)); | |
while(!Q.empty()) | |
{ | |
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 < g[x].size(); ++i) | |
{ | |
y = g[x][i].second; | |
if(marked[y] == false) | |
Q.push(g[x][i]); | |
} | |
} | |
return minimumCost; | |
} | |
int main() | |
{ | |
int n,m; | |
scanf("%d%d",&n,&m); | |
int x,y; | |
long long w; | |
for(int i=0;i<m;i++){ | |
scanf("%d%d%lld",&x,&y,&w); | |
g[x].push_back(make_pair(w,y)); | |
g[y].push_back(make_pair(w,x)); | |
} | |
long long int lowcost=prim(1); | |
printf("%lld",lowcost); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment