bellman_ford
作者:
ysc
,
2021-07-28 11:21:12
,
所有人可见
,
阅读 341
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510, M = 10010;
int n, m, k;
int dist[N]; //每个点到起点的距离数组
int backup[N]; //记录上一次结果的数组
struct Edge //定义结构体来存储
{
int a, b, w;
}edges[M];
int bellman_ford()
{
memset(dist, 0x3f, sizeof dist); //初始化距离
dist[1] = 0;
for ( int i = 0; i < k; i ++ ) //进行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;
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 ( t == -1 ) puts("impossible");
else cout << t << endl;
return 0;
}