AcWing 849. Dijkstra求最短路 I
原题链接
简单
作者:
啊冰
,
2024-04-23 22:25:45
,
所有人可见
,
阅读 1
#include <iostream>
#include <cstring>
using namespace std;
const int N = 510, M = 1E5+10;
int n, m;
int g[N][N]; // 存储节点
int dist[N]; // 当前点n到原点的最短距离
bool st[N]; // 当前点是否被遍历到
int 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 ++) // 得到最短距离的点t
if(!st[j] && (t == -1 || dist[j] < dist[t]))
t = j;
st[t] = true;
for(int j = 1; j <= n; j ++) // 用t来更新后面的点的最短距离
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
if(dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
int main() {
cin >> n >> m;
memset(g, 0x3f, sizeof g);
while(m --) {
int a, b, c;
cin >> a >> b >> c;
g[a][b] = min(g[a][b], c);
}
int t = dijkstra();
cout << t << endl;
return 0;
}