-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dijkstra.cpp
63 lines (51 loc) · 1.19 KB
/
Dijkstra.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
#define ll long long
#define pll pair<long long,long long>
#define inf 1e18
ll n,m;
vector<ll>dis,par,path;
vector<vector<pll> > adj(100005);
void dijkstra( ll s)
{
dis.assign(adj.size(), inf);
par.assign(adj.size(), -1);
dis[s]=0;
priority_queue<pll,vector<pll> , greater<pll> >q;
q.push({0,s});
while(!q.empty())
{
ll distance=q.top().first;
ll node=q.top().second;
q.pop();
if(distance!=dis[node])
{
continue;
}
for(ll k=0;k<adj[node].size();k++)
{
ll nxt_node=adj[node][k].first;
ll len=adj[node][k].second;
if(dis[nxt_node]> dis[node]+len)
{
dis[nxt_node]=dis[node]+len;
par[nxt_node]=node;
q.push({dis[nxt_node],nxt_node});
}
}
}
}
void print_path(ll src)
{
for(ll i=n;i!=src;i=par[i])
{
path.push_back(i);
}
path.push_back(src);
reverse(path.begin(),path.end());
for(ll i=0;i<path.size();i++)
{
cout<<path[i]<<" ";
}
cout<<endl;
}
dijkstra(src);
print_path(src);