853. 有边数限制的最短路 O(nm)
作者:
闪回
,
2024-03-24 19:48:36
,
所有人可见
,
阅读 3
记得备份dist数组,每次遍历所有边
#include<bits/stdc++.h>
using namespace std;
const int N = 510;
const int M = 1e4+10;
int n,m,k;
//结构体存边,包括端点和长度
struct Edge
{
int a,b,w;
}edges[M];
int dist[N],backup[N];
int bellman_ford()
{
memset(dist,0x3f,sizeof dist);
dist[1] = 0;
for(int j = 0;j<k;j++)
{
memcpy(backup,dist,sizeof dist);
for(int i = 0;i<m;i++)
{
int a = edges[i].a,b = edges[i].b,w = edges[i].w;
dist[b] = min(dist[b],backup[a] + w);
}
}
if(dist[n] > 0x3f3f3f3f/2)return 0x3f3f3f3f;
else 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};
}
if(bellman_ford() == 0x3f3f3f3f)puts("impossible");
else cout<<bellman_ford()<<endl;
return 0;
}