diff --git a/problems/kamacoder/0096.城市间货物运输III.md b/problems/kamacoder/0096.城市间货物运输III.md index feaaa1f3..dacd23d1 100644 --- a/problems/kamacoder/0096.城市间货物运输III.md +++ b/problems/kamacoder/0096.城市间货物运输III.md @@ -636,6 +636,71 @@ dijkstra 是贪心的思路 每一次搜索都只会找距离源点最近的非 ## 其他语言版本 ### Java +```Java +import java.util.*; + +public class Main { + // 基于Bellman_for一般解法解决单源最短路径问题 + // Define an inner class Edge + static class Edge { + int from; + int to; + int val; + public Edge(int from, int to, int val) { + this.from = from; + this.to = to; + this.val = val; + } + } + + public static void main(String[] args) { + // Input processing + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + int m = sc.nextInt(); + + List graph = new ArrayList<>(); + + for (int i = 0; i < m; i++) { + int from = sc.nextInt(); + int to = sc.nextInt(); + int val = sc.nextInt(); + graph.add(new Edge(from, to, val)); + } + + int src = sc.nextInt(); + int dst = sc.nextInt(); + int k = sc.nextInt(); + + int[] minDist = new int[n + 1]; + int[] minDistCopy; + + Arrays.fill(minDist, Integer.MAX_VALUE); + minDist[src] = 0; + + for (int i = 0; i < k + 1; i++) { // Relax all edges k + 1 times + minDistCopy = Arrays.copyOf(minDist, n + 1); + for (Edge edge : graph) { + int from = edge.from; + int to = edge.to; + int val = edge.val; + // Use minDistCopy to calculate minDist + if (minDistCopy[from] != Integer.MAX_VALUE && minDist[to] > minDistCopy[from] + val) { + minDist[to] = minDistCopy[from] + val; + } + } + } + + // Output printing + if (minDist[dst] == Integer.MAX_VALUE) { + System.out.println("unreachable"); + } else { + System.out.println(minDist[dst]); + } + } +} + +``` ### Python