本文主要是介绍最短路:Bellman-Ford,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最短路:Bellman-Ford
- 题目描述
- 参考代码
题目描述
输入样例
3 3 1
1 2 1
2 3 1
1 3 3
输出样例
3
参考代码
#include <iostream>
#include <cstring>
#include <algorithm>using namespace std;const int N = 510, M = 10010;int n, m, k;
int dist[N], backup[N]; // 需要备份struct
{int a, b, w;
} edges[M];int 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);}}if (dist[n] > 0x3f3f3f3f / 2) return -1;return dist[n];
}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};}int ans = bellman_ford();printf("%d\n", ans);return 0;
}
这篇关于最短路:Bellman-Ford的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!