-
Notifications
You must be signed in to change notification settings - Fork 1
/
dijkstra.cpp
40 lines (35 loc) · 862 Bytes
/
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
/* Dijkstra's Single Source Shortest Path Algorithm
* Number of Vertices: n
* Source: s
* Distance Array: dist[]
* Adjacency List: adj[][] tuple(vertex, weight)
* Infinte Constant: inf
*/
void dijkstra()
{
for(int i=0;i<n;++i)
{
dist[i] = inf;
}
set< tuple<int,int> > q;
dist[s] = 0;
q.insert(make_tuple(0,s));
while(!q.empty())
{
int u = get<1>(*q.begin());
for(int i=0; i<adj[u].size(); ++i)
{
int v = get<0>(adj[u][i]);
int w = get<1>(adj[u][i]);
if(dist[v] > dist[u]+w)
{
if(dist[v] != inf)
{
q.erase(q.find(make_tuple(dist[v],v)));
}
dist[v] = dist[u]+w;
q.insert(make_tuple(dist[v],v));
}
}
}
}