From ab6cb84cb905dc3ededa4165653435afd38c34ed Mon Sep 17 00:00:00 2001 From: Allen Guo Date: Thu, 8 Aug 2024 17:14:40 -0700 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B00096.=E5=9F=8E=E5=B8=82?= =?UTF-8?q?=E9=97=B4=E8=B4=A7=E7=89=A9=E8=BF=90=E8=BE=93III=20=E5=9F=BA?= =?UTF-8?q?=E4=BA=8EBellman=5Fford=E4=B8=80=E8=88=AC=E8=A7=A3=E6=B3=95Java?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0096.城市间货物运输III.md | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) 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