AcWing 853. 有边数限制的最短路
Bellman-Ford
基于迭代思想的暴力,而非贪心
// 853.有边数限制的最短路
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510;
const int M = 10010;
const int INF = 0x3f3f3f3f;
int head[N],e[M],w[M],net[M],cnt;
int n,m,k;
int dis[N],temp[N];
void init() {
cnt=0;
fill(head,head+N,0);
return;
}
void addedge(int x, int y, int z) {
++cnt;
e[cnt]=y;
w[cnt]=z;
net[cnt]=head[x];
head[x]=cnt;
return;
}
void bellmanford() {
fill(dis,dis+N,INF);
dis[1]=0;
for(int i=1;i<=k;++i) {
for(int x=1;x<=n;++x) temp[x]=dis[x];
for(int x=1;x<=n;++x) {
for(int p=head[x];p;p=net[p]) {
int y=e[p];
int z=w[p];
if(temp[x]!=INF&&dis[y]>temp[x]+z) {
dis[y]=temp[x]+z;
}
}
}
}
return;
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
init();
scanf("%d%d%d",&n,&m,&k);
for(int i=0;i<m;++i) {
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
addedge(x,y,z);
}
bellmanford();
if(dis[n]==INF) printf("impossible");
else printf("%d",dis[n]);
return 0;
}