結果

問題 No.2565 はじめてのおつかい
ユーザー kinoko_econ
提出日時 2023-12-02 16:15:13
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 692 ms / 2,000 ms
コード長 1,210 bytes
コンパイル時間 423 ms
コンパイル使用メモリ 81,920 KB
実行使用メモリ 99,652 KB
最終ジャッジ日時 2024-09-26 20:03:03
合計ジャッジ時間 21,055 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #

N, M = map(int,input().split())
G = [[] for _ in range(N)]
for i in range(M):
    u, v = map(int,input().split())
    G[u-1].append([v-1, 1])

## ダイクストラ法の実装
## 「ある頂点から全ての頂点への最短距離」をO(E*logV)で出力できる。
## 辺の長さはバラバラで、非負の値。

import heapq

def dijkstra(V, G, r):
    done = [False]*V
    dist = [10**10]*V
    dist[r] = 0
    node_heap = []
    heapq.heappush(node_heap, [dist[r], r])

    while node_heap:
        tmp = heapq.heappop(node_heap)
        cur_node = tmp[1]
        if not done[cur_node]:
            for e in G[cur_node]:
                if dist[e[0]] > dist[cur_node] + e[1]:
                    dist[e[0]] = dist[cur_node] + e[1]
                    heapq.heappush(node_heap, [dist[e[0]], e[0]])
        done[cur_node] = True
    return dist

ans = 10**15
d1 = dijkstra(N, G, 0)
d2 = dijkstra(N, G, N-2)
d3 = dijkstra(N, G, N-1)
if d1[N-2] < 10**10 and d2[N-1] < 10**10 and d3[0] < 10**10:
    ans = min(ans, d1[N-2] + d2[N-1] + d3[0])
if d1[N-1] < 10**10 and d3[N-2] < 10**10 and d2[0] < 10**10:
    ans = min(ans, d1[N-1] + d3[N-2] + d2[0])
if ans < 10**15:
    print(ans)
else:
    print(-1)
0