C++
$\color{#cc33ff}{— > 算法基础课题解}$
Bellman-Ford算法 思想(两重循环):
1、第一重循环n次
2、第二重循环所有边,每次循环的时候更新一下最短距离
$图解:$
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510, M = 1e4 + 10;
int n, m, k;
int dist[N], backup[N];
struct Edge {
int a, b, w;
}edges[M]; // 用结构体edges[i]来表示一条从a到b的边,边长为w
int bellman_ford() {
memset(dist, 0x3f, sizeof dist); // 初始化
dist[1] = 0;
for (int i = 0; i < k; i ++) { // 不超过k条边的最短距离,迭代k次
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; // 数据加强了,会有一种最短距离是-1的情况
// return dist[n];
}
int main() {
cin >> n >> m >> k;
for (int i = 0; i < m; i ++) {
int a, b, w;
cin >> a >> b >> w;
edges[i] = {a, b, w};
}
int t = bellman_ford();
if (dist[n] > 0x3f3f3f3f / 2) cout << "impossible";
else cout << dist[n];
return 0;
}