結果

問題 No.2565 はじめてのおつかい
ユーザー loop0919loop0919
提出日時 2023-11-03 15:48:30
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 463 ms / 2,000 ms
コード長 915 bytes
コンパイル時間 135 ms
コンパイル使用メモリ 12,128 KB
実行使用メモリ 35,344 KB
最終ジャッジ日時 2023-11-03 15:48:48
合計ジャッジ時間 17,255 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 25 ms
10,200 KB
testcase_01 AC 25 ms
10,200 KB
testcase_02 AC 26 ms
10,200 KB
testcase_03 AC 463 ms
35,344 KB
testcase_04 AC 385 ms
35,096 KB
testcase_05 AC 27 ms
10,200 KB
testcase_06 AC 281 ms
15,676 KB
testcase_07 AC 160 ms
13,132 KB
testcase_08 AC 142 ms
13,792 KB
testcase_09 AC 243 ms
15,012 KB
testcase_10 AC 165 ms
14,428 KB
testcase_11 AC 365 ms
20,728 KB
testcase_12 AC 119 ms
11,828 KB
testcase_13 AC 173 ms
14,000 KB
testcase_14 AC 274 ms
17,360 KB
testcase_15 AC 291 ms
17,064 KB
testcase_16 AC 280 ms
22,896 KB
testcase_17 AC 80 ms
12,076 KB
testcase_18 AC 92 ms
14,964 KB
testcase_19 AC 317 ms
19,456 KB
testcase_20 AC 283 ms
18,692 KB
testcase_21 AC 272 ms
18,764 KB
testcase_22 AC 174 ms
15,668 KB
testcase_23 AC 185 ms
15,800 KB
testcase_24 AC 52 ms
11,284 KB
testcase_25 AC 287 ms
18,880 KB
testcase_26 AC 188 ms
15,488 KB
testcase_27 AC 285 ms
19,420 KB
testcase_28 AC 316 ms
19,272 KB
testcase_29 AC 354 ms
21,500 KB
testcase_30 AC 309 ms
20,220 KB
testcase_31 AC 287 ms
19,144 KB
testcase_32 AC 173 ms
15,340 KB
testcase_33 AC 319 ms
19,704 KB
testcase_34 AC 316 ms
18,244 KB
testcase_35 AC 303 ms
21,388 KB
testcase_36 AC 299 ms
19,764 KB
testcase_37 AC 179 ms
15,708 KB
testcase_38 AC 320 ms
18,264 KB
testcase_39 AC 252 ms
16,800 KB
testcase_40 AC 335 ms
21,432 KB
testcase_41 AC 346 ms
22,336 KB
testcase_42 AC 201 ms
15,288 KB
testcase_43 AC 264 ms
17,524 KB
testcase_44 AC 145 ms
13,848 KB
testcase_45 AC 88 ms
12,340 KB
testcase_46 AC 304 ms
17,408 KB
testcase_47 AC 225 ms
14,188 KB
testcase_48 AC 186 ms
13,860 KB
testcase_49 AC 115 ms
11,788 KB
testcase_50 AC 279 ms
14,716 KB
testcase_51 AC 24 ms
10,200 KB
testcase_52 AC 268 ms
11,892 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque

INF = 1 << 60

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

graph = [[] for _ in range(N)]

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

def bfs(start):
    dists = [INF]*N
    dists[start] = 0
    
    que = deque([(start, 0)])
    
    while que:
        now, d = que.popleft()
        
        for next in graph[now]:
            if dists[next] < INF:
                continue
            dists[next] = d + 1
            que.append((next, d + 1))
    
    return dists

di = {
    0: bfs(0),
    N - 2: bfs(N - 2),
    N - 1: bfs(N - 1)
}

# 町1 -> 町N-1 -> 町N -> 町1 の最短経路の長さ
ans_1 = di[0][N - 2] + di[N - 2][N - 1] + di[N - 1][0]

# 町1 -> 町N -> 町N-1 -> 町1 の最短経路の長さ
ans_2 = di[0][N - 1] + di[N - 1][N - 2] + di[N - 2][0]

ans = min(ans_1, ans_2)

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