forked from akhiluanandh/utility-functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.cpp
72 lines (65 loc) · 1.3 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
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <vector>
#include <queue>
#define MAX 10000
#define INF 100000000
#define traverse(container, it) \
for(typeof(container.begin()) it = container.begin(); it != container.end(); it++)
using namespace std;
typedef pair<int, int> ii;
int depths[MAX+1];
vector<ii> adj[MAX+1];
bool completed[MAX+1];
struct MinHeap
{
bool operator()(int a, int b)
{
return depths[a] > depths[b];
}
};
int dijkstra(int source, int dest)
{
int temp, newv, cost;
depths[source] = 0;
priority_queue<int, vector<int>, MinHeap> Q;
Q.push(source);
while(!Q.empty())
{
temp = Q.top();
Q.pop();
if(completed[temp])
continue;
completed[temp] = true;
if(temp == dest)
return depths[dest];
traverse(adj[temp], w)
{
newv = (*w).first;
cost = (*w).second;
if(completed[newv])
continue;
if(depths[temp] + cost < depths[newv])
{
depths[newv] = depths[temp] + cost;
Q.push(newv);
}
}
}
return 0;
}
int main()
{
int n, m, source, dest, a, b, c;
cin>>n;
for(int i = 0; i <= n; i++)
depths[i] = INF;
cin>>m;
for(int i = 0; i < m; i++)
{
cin>>a>>b>>c;
adj[a].push_back(ii(b, c));
adj[b].push_back(ii(a, c));
}
cin>>source>>dest;
cout<<dijkstra(source, dest)<<"\n";
}