Repository navigation
Expand file tree
/
Copy pathprims.cpp
More file actions
65 lines (64 loc) · 1.45 KB
/
Copy pathprims.cpp
File metadata and controls
65 lines (64 loc) · 1.45 KB
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
65
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> p;
void prims(vector<p> adj[],int s,int n)
{
priority_queue<p,vector<p>,greater<p>> pq;
int dis[n],parent[n];
bool visit[n];
for(int i=0;i<n;i++)
{
dis[i]=INT_MAX;
parent[i]=-1;
visit[i]=true;
}
pq.push(make_pair(0,s));
dis[s]=0;
parent[s]=s;
while(!pq.empty())
{
int u=pq.top().second;
pq.pop();
//cout<<u<<"vertex";
visit[u]=false;
for(auto x:adj[u])
{
int v=x.first;
int w=x.second;
//cout<<v<<" "<<w<<" " <<pq.top().first<<" "<<pq.top().second<<endl;
if(visit[v] && dis[v]>w)
{
dis[v]=w;
pq.push(make_pair(dis[v],v));
parent[v]=u;
}
}
}
cout<<"here"<<endl;
for(int i=1;i<n;i++)
{
cout<<parent[i]<<" "<<i<<endl;
}
cout<<endl;
}
int main()
{
int n,st,ed,e,i,wt;
cout<<"Enter the no of vertices"<<endl;
cin>>n;
vector<p> adj[n];
cout<<"Enter the no of edges"<<endl;
cin>>e;
for(i=0;i<e;i++)
{
//cout<<"Enter the start"<<i+1<<endl;
cin>>st;
//cout<<"Enter the end"<<i+1<<endl;
cin>>ed;
//cout<<"Enter the weight"<<i+1<<endl;
cin>>wt;
adj[st].push_back(make_pair(ed,wt));
//adj[ed].push_back(make_pair(st,wt));
}
prims(adj,0,n);
}