結果

問題 No.160 最短経路のうち辞書順最小
ユーザー lam6er
提出日時 2025-04-15 22:46:17
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,286 bytes
コンパイル時間 303 ms
コンパイル使用メモリ 82,336 KB
実行使用メモリ 75,556 KB
最終ジャッジ日時 2025-04-15 22:48:04
合計ジャッジ時間 2,909 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 8 WA * 18
権限があれば一括ダウンロードができます

ソースコード

diff #

import heapq

def main():
    import sys
    input = sys.stdin.read().split()
    idx = 0
    n = int(input[idx]); idx +=1
    m = int(input[idx]); idx +=1
    S = int(input[idx]); idx +=1
    G = int(input[idx]); idx +=1

    adj = [[] for _ in range(n)]
    for _ in range(m):
        a = int(input[idx]); idx +=1
        b = int(input[idx]); idx +=1
        c = int(input[idx]); idx +=1
        adj[a].append((b, c))
        adj[b].append((a, c))

    INF = 1 << 60
    dist = [INF] * n
    prev = [-1] * n
    dist[S] = 0
    heap = []
    heapq.heappush(heap, (0, S))

    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue
        for v, c in adj[u]:
            new_dist = d + c
            if new_dist < dist[v]:
                dist[v] = new_dist
                prev[v] = u
                heapq.heappush(heap, (new_dist, v))
            elif new_dist == dist[v]:
                if prev[v] == -1 or u < prev[v]:
                    prev[v] = u
                    heapq.heappush(heap, (new_dist, v))

    # Reconstruct path
    path = []
    current = G
    while current != -1:
        path.append(current)
        current = prev[current]
    path.reverse()

    print(' '.join(map(str, path)))

if __name__ == "__main__":
    main()
0