C++ 代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 510, M = 1e4+10;
int last[N], dist[N], n, m, k;
struct node{
int a, b, c;
}edge[M];
void bellman_ford()
{
//初始化不能忘!
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
//一共更新K次
for(int i = 0; i < k; i++)
{
//备份一下
memcpy(last, dist, sizeof(dist));
for(int j = 0; j < m; j++)
{
node e = edge[j];
dist[e.b] = min(dist[e.b] , last[e.a] + e.c);
}
}
}
int main()
{
scanf("%d%d%d", &n, &m, &k);
for(int i = 0; i < m; i++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
edge[i] = {a, b, c};
}
bellman_ford();
//存在负权边,所以n点不一定是正无穷
if(dist[n] > 0x3f3f3f3f / 2) puts("impossible");
else printf("%d\n", dist[n]);
return 0;
}