結果

問題 No.2565 はじめてのおつかい
ユーザー loop0919loop0919
提出日時 2023-10-31 15:21:40
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 191 ms / 2,000 ms
コード長 912 bytes
コンパイル時間 191 ms
コンパイル使用メモリ 81,840 KB
実行使用メモリ 89,848 KB
最終ジャッジ日時 2023-10-31 15:21:50
合計ジャッジ時間 9,683 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 41 ms
55,664 KB
testcase_01 AC 44 ms
55,664 KB
testcase_02 AC 40 ms
55,664 KB
testcase_03 AC 188 ms
89,848 KB
testcase_04 AC 148 ms
89,848 KB
testcase_05 AC 40 ms
55,664 KB
testcase_06 AC 149 ms
79,700 KB
testcase_07 AC 112 ms
77,924 KB
testcase_08 AC 113 ms
78,928 KB
testcase_09 AC 139 ms
79,012 KB
testcase_10 AC 133 ms
79,212 KB
testcase_11 AC 185 ms
84,084 KB
testcase_12 AC 98 ms
76,648 KB
testcase_13 AC 118 ms
78,424 KB
testcase_14 AC 149 ms
81,444 KB
testcase_15 AC 151 ms
80,828 KB
testcase_16 AC 141 ms
85,588 KB
testcase_17 AC 83 ms
77,172 KB
testcase_18 AC 88 ms
79,204 KB
testcase_19 AC 177 ms
83,028 KB
testcase_20 AC 152 ms
82,260 KB
testcase_21 AC 150 ms
82,380 KB
testcase_22 AC 118 ms
80,436 KB
testcase_23 AC 123 ms
80,232 KB
testcase_24 AC 83 ms
77,180 KB
testcase_25 AC 157 ms
82,516 KB
testcase_26 AC 131 ms
79,888 KB
testcase_27 AC 147 ms
82,924 KB
testcase_28 AC 167 ms
82,872 KB
testcase_29 AC 184 ms
84,812 KB
testcase_30 AC 164 ms
83,508 KB
testcase_31 AC 169 ms
82,528 KB
testcase_32 AC 126 ms
80,056 KB
testcase_33 AC 174 ms
83,232 KB
testcase_34 AC 174 ms
81,700 KB
testcase_35 AC 157 ms
84,512 KB
testcase_36 AC 172 ms
83,220 KB
testcase_37 AC 128 ms
80,160 KB
testcase_38 AC 165 ms
81,720 KB
testcase_39 AC 152 ms
80,888 KB
testcase_40 AC 184 ms
84,700 KB
testcase_41 AC 191 ms
85,424 KB
testcase_42 AC 129 ms
79,632 KB
testcase_43 AC 149 ms
81,276 KB
testcase_44 AC 123 ms
79,072 KB
testcase_45 AC 96 ms
77,516 KB
testcase_46 AC 165 ms
80,932 KB
testcase_47 AC 132 ms
78,672 KB
testcase_48 AC 128 ms
78,872 KB
testcase_49 AC 98 ms
76,660 KB
testcase_50 AC 140 ms
78,380 KB
testcase_51 AC 40 ms
55,664 KB
testcase_52 AC 117 ms
77,016 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