AcWing 849. Dijkstra求最短路 I
原题链接
简单
作者:
Value
,
2020-05-22 14:38:24
,
所有人可见
,
阅读 505
#include <iostream>
#include <cstring>
using namespace std;
const int N = 510;
int graph[N][N];
bool st[N];
int dist[N];
int n, m;
int dijkstra(){
memset(dist, 0x3f3f3f, sizeof dist);
dist[1] = 0;
for(int i = 0; i < n; i ++ ){
int nxt = -1;
// 找到距离当前起点的最近的点
for(int j = 1;j <= n; j ++ ){
if(!st[j] && (nxt == -1 || dist[nxt] > dist[j])) nxt = j;
}
st[nxt] = true;
// 用nxt点去更新集合内的其他距离
for(int j = 1; j <= n; j ++ ){
if(dist[j] > dist[nxt] + graph[nxt][j]){
dist[j] = dist[nxt] + graph[nxt][j];
}
}
}
if(dist[n] >= 0x3f3f3f) return -1;
return dist[n];
}
int main(){
cin >> n >> m;
memset(graph, 0x3f3f3f, sizeof graph);
int x, y, z;
for(int i = 0; i < m; i ++ ){
cin >> x >> y >> z;
graph[x][y] = min(graph[x][y], z);
}
cout << dijkstra() << endl;
return 0;
}