spfa算法是bellman_ford的队列优化版本, bfs实现
优化的是dist[b] = min(dist[b], dist[a]+w)
因为只有dist[a]
更新之后变小, dist[b]
更新之后才有可能变小
需要st[i]
数组,保证队列里面只有一个i
;
spfa是优化版的bellman_ford算法
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 1e5 + 10;
int h[N], e[N], w[N], ne[N], idx;
int n, m;
queue<int> q;
int st[N], dist[N];
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int spfa() {
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
q.push(1);
st[1] = true;
while (q.size()) {
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[t] + w[i]) {
dist[j] = dist[t] + w[i];
if (!st[j]) {
st[j] = true;
q.push(j);
}
}
}
}
// int dist[n]=t;
if (dist[n] > 0x3f3f3f3f / 2) return -1;
else return dist[n];
}
int main() {
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
int t = spfa();
if (t == -1) cout << "impossible" << endl;
else cout << t << endl;
}
楼主main忘记return 0
数据加强了,代码现在过不了了
图很好 我抄一下哈