/
DijkstrasApgo.cpp
69 lines (64 loc) · 1.53 KB
/
DijkstrasApgo.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
65
66
67
68
69
#include<bits/stdc++.h>
using namespace std;
void dijkstras()
{
int v,n_edges;
cout<<"enter number of vertices and number of edges : "<<endl;
cin>>v>>n_edges;
vector<pair<int,int>>adj[v];
for(int i=0;i<n_edges;i++)
{
int u,v,wt;
cout<<"enter start end weight :"<<endl;
cin>>u>>v>>wt;
adj[u].push_back({v,wt});
adj[v].push_back({u,wt});
}
vector<int> distance(v,1e9);
vector<int> parent(v,-1);
for(int i=0;i<v;i++)parent[i]=i;
priority_queue<pair<int,int>,vector<pair<int,int>>, greater<pair<int,int>>> pq;
int S;
cout<<"enter starting node :"<<endl;
cin>>S;
parent[S]=-1;
distance[S]=0;
pq.push({0,S});
while(!pq.empty())
{
int node=pq.top().second;
int dist=pq.top().first;
pq.pop();
for(auto x:adj[node])
{
int next_node=x.first;
int wt=x.second;
if(dist+wt<distance[next_node])
{
distance[next_node]=dist+wt;
pq.push({dist+wt,next_node});
parent[next_node]=node;
}
}
}
for(int i=0;i<v;i++)
{
if(i!=S)
{
cout<<"distance of "<<i<<"th node is : "<<distance[i]<<endl;
cout<<"path follows : "<<i;
int j=parent[i];
do
{
cout<<" <- "<<j;
j=parent[j];
}while(j!=-1);
cout<<endl;
}
}
}
int main()
{
dijkstras();
return 0;
}