AcWing 850. Dijkstra求最短路 II
原题链接
简单
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 150010;
int h[N], e[N], w[N], ne[N], idx;
int n, m;
int dist[N];
int st[N];
void add(int a, int b, int c) {
e[idx] = b; w[idx] = c; ne[idx] = h[a]; h[a] = idx++;
}
int dijkstra() {
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
priority_queue<PII,vector<PII>, greater<PII>> heap;
heap.push({0, 1});
st[1] = 1;
while (heap.size()) {
auto t = heap.top();
heap.pop();
int ver = t.second;
int distance = t.first;
// 如果ver已经更新过其他点了,就不用他再更新一遍了
if (st[ver]) continue;
st[ver] = 1;
for (int i = h[ver]; i != -1; i = ne[i]) {
int j = e[i];
// 这里是用当前最短的源点去更新其他点
if (dist[j] > distance + w[i]) {
dist[j] = distance + w[i];
// if (!st[j]) {
heap.push({dist[j], j});
// st[j] = 1;
//这里是不对的,st的含义是更新过其他点的点,而这里的含义是被更新过的点
// }
}
}
}
if (dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
int main() {
cin >> n >> m;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
int t = dijkstra();
// for (int i = 1; i <= n; i++) cout << dist[i] << endl;
cout << t << endl;
return 0;
}