AcWing 853. 有边数限制的最短路
原题链接
简单
作者:
Astarion
,
2021-02-14 10:42:44
,
所有人可见
,
阅读 267
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
class Main {
static class Edege {
int start, end, weight;
public Edege(int start, int end, int weight) {
this.start = start;
this.end = end;
this.weight = weight;
}
}
static final int INF = Integer.MAX_VALUE / 2;
static int n, m, k;
static int[] dist = new int[510];
static Edege[] edeges = new Edege[10010];
static {
Arrays.fill(dist, INF);
}
static boolean generateDistance() {
dist[1] = 0;
//循环次数即是走过的边的最大条数
for (int i = 0; i < k; i++) {
int[] temp = Arrays.copyOf(dist, n + 1);
for (int j = 0; j < m; j++) {
Edege edege = edeges[j];
//对比当前dist用上次状态的点是否可以更新
dist[edege.end] = Math.min(dist[edege.end], temp[edege.start] + edege.weight);
/*if (dist[edege.end] > temp[edege.start] + edege.weight) {
dist[edege.end] = temp[edege.start] + edege.weight;
}*/
}
}
return dist[n] <= INF / 2;
}
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
n = Integer.parseInt(strs[0]);
m = Integer.parseInt(strs[1]);
k = Integer.parseInt(strs[2]);
for (int i = 0; i < m; i++) {
strs = in.readLine().split(" ");
int a = Integer.parseInt(strs[0]);
int b = Integer.parseInt(strs[1]);
int w = Integer.parseInt(strs[2]);
edeges[i] = new Edege(a, b, w);
}
if (generateDistance()) System.out.println(dist[n]);
else System.out.println("impossible");
in.close();
isr.close();
}
}