From 92c491a6c508abf92719d21e013129c0e30532a9 Mon Sep 17 00:00:00 2001 From: Shengjie Xu Date: Wed, 5 Nov 2025 12:17:20 -0500 Subject: [PATCH] Optimize Bellman-Ford algorithm with in_queue tracking O(n) -> O(1) --- ...350\264\247\347\211\251\350\277\220\350\276\223II.md" | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git "a/problems/kamacoder/0095.\345\237\216\345\270\202\351\227\264\350\264\247\347\211\251\350\277\220\350\276\223II.md" "b/problems/kamacoder/0095.\345\237\216\345\270\202\351\227\264\350\264\247\347\211\251\350\277\220\350\276\223II.md" index 736fd6dcee..1f7e17c400 100644 --- "a/problems/kamacoder/0095.\345\237\216\345\270\202\351\227\264\350\264\247\347\211\251\350\277\220\350\276\223II.md" +++ "b/problems/kamacoder/0095.\345\237\216\345\270\202\351\227\264\350\264\247\347\211\251\350\277\220\350\276\223II.md" @@ -502,18 +502,21 @@ def main(): min_dist[1] = 0 # 初始化 count[1] = 1 d = deque([1]) + in_queue = [False for _ in range(n+1)] flag = False while d: # 主循环 cur_node = d.popleft() + in_queue[cur_node] = False for next_node, val in graph[cur_node]: if min_dist[next_node] > min_dist[cur_node] + val: min_dist[next_node] = min_dist[cur_node] + val - if next_node not in d: + if not in_queue[next_node]: count[next_node] += 1 d.append(next_node) - if count[next_node] == n: # 如果某个点松弛了n次,说明有负回路 - flag = True + in_queue[next_node] = True + if count[next_node] == n: # 如果某个点松弛了n次,说明有负回路 + flag = True if flag: break