1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import java.util.*; class Main{ static int N = 10010; static Node[] node = new Node[N]; static int[] dist = new int[N]; static int inf = 1000000000; public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); for(int i = 1; i <= m; i++){ int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); node[i] = new Node(a, b, c); } int result = bellmanFord(node, n, m, k); if(result == -1){ System.out.print("impossible"); }else{ System.out.print(result); } } public static int bellmanFord(Node[] node, int n, int m, int k){ Arrays.fill(dist, inf); dist[1] = 0; for(int i = 1; i <= k; i++){ int[] d = Arrays.copyOf(dist, N); for(int j = 1; j <= m; j++){ int a = node[j].a; int b = node[j].b; int c = node[j].c; dist[b] = Math.min(dist[b], d[a] + c); } } return dist[n] > inf/2 ? -1 : dist[n]; } }
class Node{ public int a; public int b; public int c; public Node(int a, int b, int c){ this.a = a; this.b = b; this.c = c; } }
|