知识概览
- Bellman_Ford算法适合解决存在负权边的最短路问题,时间复杂度为O(nm)。
- 在存在负权边的最短路问题中,Bellman_Ford算法的效率虽然不如SPFA算法,但是Bellman_Ford算法能解决SPFA算法不能解决的经过不超过k条边的最短路问题。
例题展示
题目链接
853. 有边数限制的最短路 - AcWing题库高质量的算法题库https://www.acwing.com/problem/content/855/
代码
#include <cstring>
#include <iostream>
#include <algorithm>using namespace std;const int N = 510, M = 10010;int n, m, k;
int dist[N], backup[N];struct Edge {int a, b, w;
} edges[M];void bellman_ford()
{memset(dist, 0x3f, sizeof dist);dist[1] = 0;for (int i = 0; i < k; i++){memcpy(backup, dist, sizeof dist);for (int j = 0; j < m; j++){int a = edges[j].a, b = edges[j].b, w = edges[j].w;dist[b] = min(dist[b], backup[a] + w);}}
}int main()
{scanf("%d%d%d", &n, &m, &k);for (int i = 0; i < m; i++){int a, b, w;scanf("%d%d%d", &a, &b, &w);edges[i] = {a, b, w};}bellman_ford();if (dist[n] > 0x3f3f3f3f / 2) puts("impossible");else printf("%d\n", dist[n]);return 0;
}
参考资料
- AcWing算法基础课