-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dijkstra.cpp
45 lines (44 loc) · 1.2 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
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector< pii > vii;
#define INF 0x3f3f3f3f
vii *G; // Graph
vi D; // distance vector for storing min distance from the source.
/*=======================================*/
void dijkstra(int source, int N) {
priority_queue<pii, vector<pii>, greater<pii> > Q; // min heap
D.assign(N,INF);
D[source] = 0;
Q.push({0,source});
while(!Q.empty()){
int u = Q.top().second;
Q.pop();
for(auto &c : G[u]){
int v = c.second;
int w = c.first;
if(D[v] > D[u]+w){
D[v] = D[u]+w;
Q.push({D[v],v});
}
}
}
}
/*==========================================*/
int main(){
int N,M,k,u,v,w;
cin >> N >> M >> k;
//Input the number of nodes(0 based), number of edges and the source vertex.
G = new vii[N];
for(int i=0;i<M;i++){
cin >> u >> v >> w;
u--;v--;
//Input the starting vertex of the edge, the ending vertex and the cost of the edge.
G[u].push_back({w,v});
G[v].push_back({w,u});
}
dijkstra(0, N);
cout<<D[N-1];
cout<<endl;
}