結果

問題 No.2565 はじめてのおつかい
ユーザー ちーぴんちーぴん
提出日時 2023-12-02 16:06:59
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 219 ms / 2,000 ms
コード長 880 bytes
コンパイル時間 494 ms
コンパイル使用メモリ 81,700 KB
実行使用メモリ 92,924 KB
最終ジャッジ日時 2023-12-02 16:07:10
合計ジャッジ時間 9,960 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 39 ms
55,608 KB
testcase_01 AC 39 ms
55,608 KB
testcase_02 AC 35 ms
55,608 KB
testcase_03 AC 178 ms
92,924 KB
testcase_04 AC 146 ms
92,288 KB
testcase_05 AC 39 ms
55,608 KB
testcase_06 AC 163 ms
80,920 KB
testcase_07 AC 131 ms
78,468 KB
testcase_08 AC 135 ms
80,024 KB
testcase_09 AC 151 ms
79,744 KB
testcase_10 AC 138 ms
80,164 KB
testcase_11 AC 219 ms
85,864 KB
testcase_12 AC 105 ms
77,316 KB
testcase_13 AC 144 ms
79,104 KB
testcase_14 AC 189 ms
83,128 KB
testcase_15 AC 173 ms
82,040 KB
testcase_16 AC 126 ms
87,616 KB
testcase_17 AC 80 ms
77,056 KB
testcase_18 AC 84 ms
80,052 KB
testcase_19 AC 185 ms
83,724 KB
testcase_20 AC 170 ms
84,084 KB
testcase_21 AC 153 ms
83,452 KB
testcase_22 AC 117 ms
81,164 KB
testcase_23 AC 144 ms
81,536 KB
testcase_24 AC 84 ms
77,060 KB
testcase_25 AC 192 ms
83,592 KB
testcase_26 AC 152 ms
81,116 KB
testcase_27 AC 131 ms
84,016 KB
testcase_28 AC 173 ms
83,192 KB
testcase_29 AC 185 ms
86,940 KB
testcase_30 AC 157 ms
84,836 KB
testcase_31 AC 177 ms
83,396 KB
testcase_32 AC 143 ms
81,512 KB
testcase_33 AC 162 ms
85,196 KB
testcase_34 AC 212 ms
82,792 KB
testcase_35 AC 151 ms
86,216 KB
testcase_36 AC 218 ms
84,948 KB
testcase_37 AC 140 ms
81,652 KB
testcase_38 AC 178 ms
83,012 KB
testcase_39 AC 179 ms
82,436 KB
testcase_40 AC 189 ms
85,908 KB
testcase_41 AC 178 ms
86,544 KB
testcase_42 AC 124 ms
80,200 KB
testcase_43 AC 164 ms
82,860 KB
testcase_44 AC 146 ms
80,148 KB
testcase_45 AC 102 ms
77,568 KB
testcase_46 AC 176 ms
82,180 KB
testcase_47 AC 133 ms
78,724 KB
testcase_48 AC 160 ms
79,752 KB
testcase_49 AC 105 ms
77,316 KB
testcase_50 AC 146 ms
79,364 KB
testcase_51 AC 36 ms
55,608 KB
testcase_52 AC 107 ms
77,048 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

"""
考察
経路のパターン
1 -> N-1 -> N -> 1
1 -> N -> N-1 -> 1
それ以外は最適にはならないのでは?
"""
from collections import deque


INF = 10**18

N, M = map(int, input().split())
G = [[] for _ in range(N)]
for _ in range(M):
    a, b = map(int, input().split())
    a -= 1; b -= 1
    G[a].append(b)


def bfs(s, t) -> int:
    dist = [INF] * N
    dist[s] = 0
    Q = deque([s])
    while Q:
        now = Q.popleft()
        if now == t:
            return dist[now]
        for nxt in G[now]:
            if dist[nxt] > dist[now] + 1:
                dist[nxt] = dist[now] + 1
                Q.append(nxt)
    return INF


S = 0
T = N-1
StoN_1 = bfs(S, T-1)
StoN = bfs(S, T)
NtoS = bfs(T, S)
N_1toS = bfs(T-1, S)
N_1toN = bfs(T-1, T)
NtoN_1 = bfs(T, T-1)

ans = min(StoN + NtoN_1 + N_1toS, StoN_1 + N_1toN + NtoS)
print(ans if ans < 10**17 else -1)
0