一、题目链接
二、题目分析
(一)算法标签
最短路 Bellman-Ford
(二)解题思路
不要忘了初始化dist, dist[1]
三、AC代码
解法一:
#include <iostream>
#include <cstring>
using namespace std;
const int N = 510, M = 1e4 +10;
struct Edge{
int a, b, w;
}edges[M];
int n, m, k;
int dist[N], backup[N];
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;
if (dist[b] > backup[a] + w)
dist[b] = backup[a] + w;
}
}
// if (dist[n] > 0x3f3f3f3f / 2) return -1;
return dist[n];
}
int main() {
cin >> n >> m >> k;
for(int i = 0; i < m; i ++ ) {
int x, y, z;
cin >> x >> y >> z;
edges[i] = {x, y, z};
}
int t = bellman_ford();
if (t > 0x3f3f3f3f / 2) puts("impossible");
else printf("%d", t);
return 0;
}