C++代码
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=510,M=10010;
int n,m,k;
int dist[N],backup[N];
struct Edge
{
int a,b,w;
}edge[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 i=0;i<m;i++)
{
int a=edge[i].a,b=edge[i].b,w=edge[i].w;
dist[b]=min(dist[b],backup[a]+w);
}
}
if(dist[n]>(0x3f3f3f3f/2)) return -1;
return dist[n];
}//bellman_ford
int main(void)
{
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);
edge[i]={a,b,w};
}
int res=bellman_ford();
if(res==-1) puts("impossible");
else printf("%d\n",res);
return 0;
}