結果

問題 No.160 最短経路のうち辞書順最小
ユーザー はむ吉🐹はむ吉🐹
提出日時 2016-07-18 15:09:39
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 130 ms / 5,000 ms
コード長 2,089 bytes
コンパイル時間 147 ms
コンパイル使用メモリ 12,672 KB
実行使用メモリ 15,616 KB
最終ジャッジ日時 2024-04-23 16:25:22
合計ジャッジ時間 2,792 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 32 ms
11,008 KB
testcase_01 AC 32 ms
11,008 KB
testcase_02 AC 32 ms
11,008 KB
testcase_03 AC 31 ms
11,008 KB
testcase_04 AC 47 ms
12,032 KB
testcase_05 AC 64 ms
13,696 KB
testcase_06 AC 85 ms
14,464 KB
testcase_07 AC 44 ms
11,520 KB
testcase_08 AC 42 ms
11,776 KB
testcase_09 AC 39 ms
11,520 KB
testcase_10 AC 43 ms
11,776 KB
testcase_11 AC 47 ms
11,904 KB
testcase_12 AC 43 ms
11,648 KB
testcase_13 AC 39 ms
11,648 KB
testcase_14 AC 42 ms
11,648 KB
testcase_15 AC 42 ms
11,648 KB
testcase_16 AC 41 ms
11,520 KB
testcase_17 AC 42 ms
11,648 KB
testcase_18 AC 44 ms
11,648 KB
testcase_19 AC 42 ms
11,648 KB
testcase_20 AC 42 ms
11,648 KB
testcase_21 AC 41 ms
11,392 KB
testcase_22 AC 40 ms
11,648 KB
testcase_23 AC 47 ms
11,776 KB
testcase_24 AC 49 ms
11,648 KB
testcase_25 AC 46 ms
11,648 KB
testcase_26 AC 43 ms
11,520 KB
testcase_27 AC 35 ms
11,136 KB
testcase_28 AC 130 ms
15,616 KB
testcase_29 AC 32 ms
11,008 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/env python3

import array
import collections
import heapq


INF = 10 ** 9
UNDEF = -1


# ゴールからスタートまでの最短経路をDijkstra法で求め、逆からたどる
def compute_optimal_path(start, goal, num_vertices, adj_edges):
    # ゴールから各頂点への最短距離を格納する
    dist = array.array("L", (INF for _ in range(num_vertices)))
    dist[goal] = 0
    # 幅優先探索順序で「ひとつ前」の頂点を格納する
    pred = array.array("i", (UNDEF for _ in range(num_vertices)))
    # 優先度付きキュー(二分ヒープ)に最短距離と頂点の組を入れる
    pq = [(dist[v], v) for v in range(num_vertices)]
    heapq.heapify(pq)
    while pq:
        _, v = heapq.heappop(pq)
        if v == start:
            # 取り出してきた頂点がスタートなら終わる
            break
        for u, cost in adj_edges[v]:
            new_length = dist[v] + cost
            if new_length < dist[u]:
                dist[u] = new_length
                pred[u] = v
                heapq.heappush(pq, (new_length, u))
            elif new_length == dist[u]:
                # 距離が同じなら、pred[]を辞書順でより小さい頂点に置き換える
                pred[u] = min(pred[u], v)
    # ここから経路復元
    # 後ろからpred[]をたどっていくと、それが求める経路になる
    path = [start]
    current = start
    while pred[current] != UNDEF:
        current = pred[current]
        path.append(current)
    return path


def main():
    num_vertices, num_edges, start, goal = map(int, input().split())
    adj_edges = [set() for _ in range(num_vertices)]
    for _ in range(num_edges):
        a, b, c = map(int, input().split())
        # 無向グラフ表すのため両向きの辺を考える
        # (行先, コスト)の組で隣接する辺を表す
        adj_edges[a].add((b, c))
        adj_edges[b].add((a, c))
    path = compute_optimal_path(start, goal, num_vertices, adj_edges)
    print(*path)


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