AcWing853-有边数限制的最短路
题目描述
给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你求出从 1 号点到 n 号点的最多经过 kk 条边的最短距离,如果无法从 1 号点走到 n 号点,输出 impossible
。
注意:图中可能 存在负权回路 。
输入格式
第一行包含三个整数 n,m,k。
接下来 m 行,每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。
输出格式
输出一个整数,表示从 1 号点到 n 号点的最多经过 k 条边的最短距离。
如果不存在满足条件的路径,则输出 impossible
。
数据范围
1≤n,k≤500
1≤m≤10000
任意边长的绝对值不超过 10000。
输入样例:
3 3 1
1 2 1
2 3 1
1 3 3
输出样例:
3
题解
package acWing853;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
class Node{
int a, b, c;
public Node(int a,int b,int c)
{
this.a = a;
this.b = b;
this.c = c;
}
}
public class Main {
static int N = 510,M = 100010;
static int n,m,k;
static int[] dist = new int[N]; // 从1到点到n号点的距离
static Node[] list = new Node[M];
static int INF = 0x3f3f3f3f;
static int[] back = new int[N]; // 备份dist数组
public static void bellman_ford(){
Arrays.fill(dist, INF);
dist[1] = 0;
for(int i = 0;i < k;i++){
back = Arrays.copyOf(dist, n + 1); // 由于是从1开始存到n
for(int j = 0;j < m;j++){
Node node = list[j];
int a = node.a,b = node.b, c = node.c;
dist[b] = Math.min(dist[b], back[a] + c);
}
}
System.out.println(dist[n] > INF/2 ? "impossible":dist[n]);
}
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String[] str = bf.readLine().split(" ");
n = Integer.parseInt(str[0]);m = Integer.parseInt(str[1]);k = Integer.parseInt(str[2]);
for(int i = 0;i < m;i++){
str = bf.readLine().split(" ");
int a = Integer.parseInt(str[0]),b = Integer.parseInt(str[1]),c = Integer.parseInt(str[2]);
list[i] = new Node(a,b,c);
}
bellman_ford();
bf.close();
}
}