結果

問題 No.2565 はじめてのおつかい
ユーザー loop0919loop0919
提出日時 2023-10-31 13:50:10
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 193 ms / 2,000 ms
コード長 1,007 bytes
コンパイル時間 331 ms
コンパイル使用メモリ 81,864 KB
実行使用メモリ 89,844 KB
最終ジャッジ日時 2023-10-31 13:50:21
合計ジャッジ時間 8,821 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 38 ms
55,664 KB
testcase_01 AC 39 ms
55,664 KB
testcase_02 AC 40 ms
55,664 KB
testcase_03 AC 193 ms
89,844 KB
testcase_04 AC 138 ms
89,844 KB
testcase_05 AC 38 ms
55,664 KB
testcase_06 AC 135 ms
79,704 KB
testcase_07 AC 106 ms
77,928 KB
testcase_08 AC 109 ms
78,928 KB
testcase_09 AC 131 ms
78,972 KB
testcase_10 AC 118 ms
79,212 KB
testcase_11 AC 162 ms
84,076 KB
testcase_12 AC 99 ms
76,644 KB
testcase_13 AC 113 ms
78,416 KB
testcase_14 AC 136 ms
81,440 KB
testcase_15 AC 140 ms
80,824 KB
testcase_16 AC 131 ms
85,576 KB
testcase_17 AC 80 ms
77,168 KB
testcase_18 AC 83 ms
79,192 KB
testcase_19 AC 151 ms
83,028 KB
testcase_20 AC 141 ms
82,260 KB
testcase_21 AC 167 ms
82,372 KB
testcase_22 AC 112 ms
80,436 KB
testcase_23 AC 113 ms
80,232 KB
testcase_24 AC 81 ms
77,184 KB
testcase_25 AC 143 ms
82,512 KB
testcase_26 AC 116 ms
79,880 KB
testcase_27 AC 137 ms
82,920 KB
testcase_28 AC 157 ms
82,872 KB
testcase_29 AC 187 ms
84,812 KB
testcase_30 AC 154 ms
83,500 KB
testcase_31 AC 151 ms
82,532 KB
testcase_32 AC 118 ms
80,044 KB
testcase_33 AC 151 ms
83,228 KB
testcase_34 AC 147 ms
81,696 KB
testcase_35 AC 145 ms
84,508 KB
testcase_36 AC 165 ms
83,216 KB
testcase_37 AC 143 ms
80,160 KB
testcase_38 AC 144 ms
81,708 KB
testcase_39 AC 143 ms
80,920 KB
testcase_40 AC 156 ms
84,688 KB
testcase_41 AC 166 ms
85,412 KB
testcase_42 AC 118 ms
79,632 KB
testcase_43 AC 134 ms
81,268 KB
testcase_44 AC 123 ms
79,036 KB
testcase_45 AC 95 ms
77,508 KB
testcase_46 AC 147 ms
80,928 KB
testcase_47 AC 122 ms
78,656 KB
testcase_48 AC 118 ms
78,872 KB
testcase_49 AC 93 ms
76,660 KB
testcase_50 AC 130 ms
78,364 KB
testcase_51 AC 38 ms
55,664 KB
testcase_52 AC 114 ms
77,012 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque

INF = 1 << 60

N, M = map(int, input().split())

# graph[u]: 町u と繋がっている町のリスト
graph = [[] for _ in range(N)]

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

# 町start からN個全ての町までの距離のリストを返す関数
def bfs(start):
    distances = [INF]*N
    distances[start] = 0
    
    que = deque([(start, 0)])
    
    while que:
        now, d = que.popleft()
        
        for next in graph[now]:
            if distances[next] < INF:
                continue
            distances[next] = d + 1
            que.append((next, d + 1))
    
    return distances

# dist[u][v]: 町u ->町v の距離 (INF ならば到達不能)
dist = {
    0: bfs(0),
    N - 2: bfs(N - 2),
    N - 1: bfs(N - 1)
}

ans = min(
    dist[0][N - 2] + dist[N - 2][N - 1] + dist[N - 1][0],
    dist[0][N - 1] + dist[N - 1][N - 2] + dist[N - 2][0]
)

if ans < INF:
	print(ans)
else:
	print(-1)
0