AcWing 851. spfa求最短路
原题链接
简单
作者:
wugensheng
,
2021-04-10 16:14:05
,
所有人可见
,
阅读 236
spfa求最短路
- dist表示每个点到源点的最短距离
- 只有当前一个点,能更新后一个点的距离点时候,才会将该点放入堆中
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010, M = 100010, INF = 0x3f3f3f3f;
int n, m;
int h[N], e[M], v[M], ne[M], cnt;
int dist[N];
bool st[N];
void spfa() {
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
queue<int> q;
q.push(1);
st[1] = true; // st表示是否在队列中
while (!q.empty()) {
auto t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; ~i; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[t] + v[i]) {
dist[j] = dist[t] + v[i];
if (!st[j]) {
q.push(j);
st[j] = true;
}
}
}
}
}
void add(int a, int b, int c) {
e[cnt] = b, ne[cnt] = h[a], v[cnt] = c, h[a] = cnt++;
}
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);
}
spfa();
if (dist[n] > INF / 2) cout << "impossible" << endl;
else cout << dist[n] << endl;
return 0;
}