結果

問題 No.160 最短経路のうち辞書順最小
ユーザー neterukunneterukun
提出日時 2020-04-02 22:45:18
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 162 ms / 5,000 ms
コード長 1,086 bytes
コンパイル時間 587 ms
コンパイル使用メモリ 87,268 KB
実行使用メモリ 80,272 KB
最終ジャッジ日時 2023-09-11 00:50:19
合計ジャッジ時間 6,186 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 76 ms
71,468 KB
testcase_01 AC 76 ms
71,468 KB
testcase_02 AC 76 ms
71,444 KB
testcase_03 AC 79 ms
71,292 KB
testcase_04 AC 162 ms
78,156 KB
testcase_05 AC 131 ms
78,296 KB
testcase_06 AC 137 ms
80,056 KB
testcase_07 AC 113 ms
78,396 KB
testcase_08 AC 112 ms
78,068 KB
testcase_09 AC 113 ms
77,948 KB
testcase_10 AC 112 ms
77,928 KB
testcase_11 AC 114 ms
77,904 KB
testcase_12 AC 114 ms
78,484 KB
testcase_13 AC 111 ms
77,864 KB
testcase_14 AC 109 ms
78,040 KB
testcase_15 AC 111 ms
77,988 KB
testcase_16 AC 115 ms
78,256 KB
testcase_17 AC 110 ms
78,140 KB
testcase_18 AC 110 ms
78,092 KB
testcase_19 AC 112 ms
78,308 KB
testcase_20 AC 116 ms
78,224 KB
testcase_21 AC 110 ms
77,916 KB
testcase_22 AC 110 ms
78,112 KB
testcase_23 AC 112 ms
78,140 KB
testcase_24 AC 118 ms
78,160 KB
testcase_25 AC 111 ms
78,232 KB
testcase_26 AC 111 ms
78,216 KB
testcase_27 AC 87 ms
75,780 KB
testcase_28 AC 136 ms
80,272 KB
testcase_29 AC 81 ms
71,560 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import heapq


def dijkstra(start: int, graph: list) -> list:
    """dijkstra法: 始点startから各頂点への最短距離を求める
    計算量: O((E+V)logV)
    """
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    q = [(0, start)] # q = [(startからの距離, 現在地)]
    while q:
        d, v = heapq.heappop(q)
        if dist[v] < d:
            continue
        for nxt_v, cost in graph[v]:
            if dist[v] + cost < dist[nxt_v]:
                dist[nxt_v] = dist[v] + cost
                heapq.heappush(q, (dist[nxt_v], nxt_v))
    return dist


n, m, s, g = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]

graph = [[] for i in range(n)]
for a, b, cost in info:
    graph[a].append((b, cost))
    graph[b].append((a, cost))

dist = dijkstra(g, graph)

ans = [s]
v = s
while True:
    if v == g:
        break
    tmp_v = 10 ** 18
    for nxt_v, cost in graph[v]:
        if dist[v] == dist[nxt_v] + cost:
            tmp_v = min(tmp_v, nxt_v)
    v = tmp_v
    ans.append(v)
print(*ans)
0