From e391a247292b798c6afe86e19cf6b691d8f2de84 Mon Sep 17 00:00:00 2001 From: kyshen Date: Fri, 6 Sep 2024 22:39:29 +0800 Subject: [PATCH 1/2] feat: 0094 python solution SPFA --- .../0094.城市间货物运输I-SPFA.md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/kamacoder/0094.城市间货物运输I-SPFA.md b/problems/kamacoder/0094.城市间货物运输I-SPFA.md index ce383919..142bb528 100644 --- a/problems/kamacoder/0094.城市间货物运输I-SPFA.md +++ b/problems/kamacoder/0094.城市间货物运输I-SPFA.md @@ -425,7 +425,44 @@ public class Main { ``` ### Python +```Python +import collections +def main(): + n, m = map(int, input().strip().split()) + edges = [] + for _ in range(m): + src, dest, weight = map(int, input().strip().split()) + edges.append([src, dest, weight]) + + minDist = [float("inf")] * (n + 1) + minDist[1] = 0 + que = collections.deque([1]) + visited = [False] * (n + 1) + visited[1] = True + + while que: + cur = que.popleft() + visited[cur] = True + updated = False + for src, dest, weight in edges: + if minDist[src] != float("inf") and minDist[src] + weight < minDist[dest]: + minDist[dest] = minDist[src] + weight + updated = True + if visited[dest] == False: + que.append(dest) + visited[dest] = True + + if not updated: + break + + if minDist[-1] == float("inf"): + return "unconnected" + return minDist[-1] + +if __name__ == "__main__": + print(main()) +``` ### Go ### Rust From e24c307c07b7f70eca2f48d01d3c56f318b82dd3 Mon Sep 17 00:00:00 2001 From: kyshen Date: Fri, 6 Sep 2024 23:59:51 +0800 Subject: [PATCH 2/2] fix: error saving the edges --- .../0094.城市间货物运输I-SPFA.md | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/problems/kamacoder/0094.城市间货物运输I-SPFA.md b/problems/kamacoder/0094.城市间货物运输I-SPFA.md index 142bb528..b3f42bf8 100644 --- a/problems/kamacoder/0094.城市间货物运输I-SPFA.md +++ b/problems/kamacoder/0094.城市间货物运输I-SPFA.md @@ -430,10 +430,10 @@ import collections def main(): n, m = map(int, input().strip().split()) - edges = [] + edges = [[] for _ in range(n + 1)] for _ in range(m): src, dest, weight = map(int, input().strip().split()) - edges.append([src, dest, weight]) + edges[src].append([dest, weight]) minDist = [float("inf")] * (n + 1) minDist[1] = 0 @@ -443,18 +443,13 @@ def main(): while que: cur = que.popleft() - visited[cur] = True - updated = False - for src, dest, weight in edges: - if minDist[src] != float("inf") and minDist[src] + weight < minDist[dest]: - minDist[dest] = minDist[src] + weight - updated = True + visited[cur] = False + for dest, weight in edges[cur]: + if minDist[cur] != float("inf") and minDist[cur] + weight < minDist[dest]: + minDist[dest] = minDist[cur] + weight if visited[dest] == False: que.append(dest) visited[dest] = True - - if not updated: - break if minDist[-1] == float("inf"): return "unconnected"