Skip to content

Instantly share code, notes, and snippets.

@lsiddiqsunny
Last active September 20, 2017 18:32
Show Gist options
  • Save lsiddiqsunny/2f376dda60f094b965ba626593dc293e to your computer and use it in GitHub Desktop.
Save lsiddiqsunny/2f376dda60f094b965ba626593dc293e to your computer and use it in GitHub Desktop.
Prim's algorithm implementation for minimum spanning tree.
#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