-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path44.Dijkstra.cpp
More file actions
45 lines (42 loc) · 818 Bytes
/
44.Dijkstra.cpp
File metadata and controls
45 lines (42 loc) · 818 Bytes
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
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 510, M = 100010;
int h[N], e[M], ne[M], w[M], idx;
int state[N];
int dist[N];
int n, m;
void add(int a, int b, int c){
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
void Dijkstra(){
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
for(int i = 0; i < n; i++){
int t = -1;
for(int j = 1; j <= n; j++){
if(!state[j] && (t == -1 || dist[j] < dist[t]))
t = j;
}
state[t] = 1;
for(int j = h[t]; j != -1; j = ne[j]){
int i = e[j];
dist[i] = min(dist[i], dist[t] + w[j]);
}
}
}
int main()
{
memset(h, -1, sizeof(h));
cin >> n >> m;
while(m--){
int a, b, w;
cin >> a >> b >> w;
add(a, b, w);
}
Dijkstra();
if(dist[n] != 0x3f3f3f3f) cout << dist[n];
else cout << "-1";
return 0;
}