-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprim's MST.cpp
64 lines (61 loc) · 1.81 KB
/
prim's MST.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//undirected graph
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
void addEdge(vector<pair<int,int> >adj[],int u,int v,int w)
{
adj[u].push_back(make_pair(v,w));
adj[v].push_back(make_pair(u,w));
}
void primMST(vector<pair<int,int> >adj[],int src,int n)
{
//make priority queue
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > pq;
vector<int>key(n,INF);
vector<int>parent(n,-1);
vector<bool>inMST(n,false);//MST set
//add source vertex to pq with key=0
pq.push(make_pair(0,src));
key[src]=0; //key of src is 0
inMST[src]=true; //add src in mst set
while(!pq.empty())
{
int u;
u=pq.top().second; //extract minimum
pq.pop(); //remove from pq
inMST[u]=true; //add in MST
//for every adjacent child of u
vector<pair<int,int> >::iterator i;
for(i=adj[u].begin();i!=adj[u].end();++i)
{
int v=(*i).first; //extract vertex
int weight=(*i).second; //extract weight
if(inMST[v]==false && key[v]>weight)
{
//update key value and add v to pq
key[v]=weight;
pq.push(make_pair(key[v],v));
parent[v]=u;
}
}
}
cout<<"Edge in MST \nparent\tchild\n";
for(int j=1;j<n;j++)
cout<<parent[j]<<"\t"<<j<<endl;
}
int main()
{
int n,e,a,b,w;
cout<<"Enter no. of node and edges";
cin>>n>>e;
vector<pair<int,int> >adj[n];
for(int i=1;i<=e;i++)
{
cin>>a>>b>>w;
addEdge(adj,a,b,w);
}
cout<<"\nEnter vertex no. where you want to find minimum spanning tree:";
int t;
cin>>t;
primMST(adj,t,n);
}