結果

問題 No.160 最短経路のうち辞書順最小
ユーザー lam6er
提出日時 2025-04-15 22:48:42
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 353 ms / 5,000 ms
コード長 1,743 bytes
コンパイル時間 272 ms
コンパイル使用メモリ 81,912 KB
実行使用メモリ 94,012 KB
最終ジャッジ日時 2025-04-15 22:50:09
合計ジャッジ時間 3,293 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

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 = float('inf')
    distances = [INF] * N
    distances[S] = 0
    paths = [None] * N
    paths[S] = [S]
    
    heap = []
    heapq.heappush(heap, (0, [S], S))
    
    found = False
    while heap:
        current_dist, current_path, current_node = heapq.heappop(heap)
        if current_node == G:
            print(' '.join(map(str, current_path)))
            found = True
            break
        if current_dist > distances[current_node]:
            continue
        if current_path != paths[current_node]:
            continue
        for neighbor, cost in adj[current_node]:
            new_dist = current_dist + cost
            new_path = current_path + [neighbor]
            if new_dist < distances[neighbor]:
                distances[neighbor] = new_dist
                paths[neighbor] = new_path.copy()
                heapq.heappush(heap, (new_dist, new_path, neighbor))
            elif new_dist == distances[neighbor]:
                if paths[neighbor] is None or new_path < paths[neighbor]:
                    paths[neighbor] = new_path.copy()
                    heapq.heappush(heap, (new_dist, new_path, neighbor))
    if not found:
        pass  # According to the problem statement, a path always exists.

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