結果

問題 No.1995 CHIKA Road
ユーザー kept1994
提出日時 2022-10-30 19:28:30
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 2,027 bytes
コンパイル時間 126 ms
コンパイル使用メモリ 82,784 KB
実行使用メモリ 160,476 KB
最終ジャッジ日時 2024-07-07 11:28:46
合計ジャッジ時間 12,014 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 31 WA * 6
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/env python3
import heapq
INF = 10 ** 16
class Dijkstra():
    def __init__(self, N: int) -> None:
        self.N = N 
        self.G = [[] for _ in range(N)]
        return
    
    # 辺の追加
    def addEdge(self, fromNode: int, toNode: int, cost: int):
        self.G[fromNode].append((cost, toNode))
        return
    
    def build(self, startNode: int):
        hq = []
        heapq.heapify(hq)
        # Set start info
        dist = [INF] * self.N
        # prev = [-1] * self.N # 経路復元する場合は移動時に直前の頂点や辺を記録して遷移していく。
        heapq.heappush(hq, (0, startNode))
        dist[startNode] = 0
        # dijkstra
        while hq:
            min_cost, now = heapq.heappop(hq)
            if min_cost > dist[now]:
                continue
            for cost, next in self.G[now]:
                if dist[next] > dist[now] + cost:
                    dist[next] = dist[now] + cost
                    # prev[next] = now # 頂点nextに至る直前の頂点を更新。
                    heapq.heappush(hq, (dist[next], next))
        return dist

def main():
    N, M = map(int, input().split())
    A, B = [], []
    city = set()
    for i in range(M):
        aa, bb = map(int, input().split())
        A.append(aa)
        B.append(bb)
        city.add(aa)
        city.add(bb)
    compressed = {}
    compressed_to_raw = []
    city.add(N)
    city = sorted(list(city))
    for index, val in enumerate(city):
        compressed[val] = index
        compressed_to_raw.append(val)
    dk = Dijkstra(len(city))
    for i in range(len(city) - 1):
        aa = city[i]
        bb = city[i + 1]
        s = compressed[aa]
        t = compressed[bb]
        d = (bb - aa) * 2
        dk.addEdge(s, t, d)
    for aa, bb in zip(A, B):
        s = compressed[aa]
        t = compressed[bb]
        d = 2 * bb - 2 * aa - 1
        dk.addEdge(s, t, d)
    res = dk.build(startNode=0)
    print(res[-1])
    return


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