結果
問題 |
No.2565 はじめてのおつかい
|
ユーザー |
|
提出日時 | 2023-12-06 11:35:35 |
言語 | PyPy3 (7.3.15) |
結果 |
RE
|
実行時間 | - |
コード長 | 1,347 bytes |
コンパイル時間 | 257 ms |
コンパイル使用メモリ | 82,332 KB |
実行使用メモリ | 306,704 KB |
最終ジャッジ日時 | 2024-09-27 01:11:46 |
合計ジャッジ時間 | 9,923 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 11 RE * 21 TLE * 1 -- * 17 |
ソースコード
from collections import defaultdict from collections import deque #import itertools def bfs(start, end): befores = deque([-1]) nows = deque([start]) cnt = 0 while True: if len(nows) == 0: return -1 cnt += 1 for _ in range(len(nows)): now = nows.popleft() for after in graph[now]: before = befores.popleft() if after == end: return cnt if after != before: nows.append(after) befores.append(now) N, M = map(int, input().split()) graph = defaultdict(list) for _ in range(M): u, v = map(int, input().split()) graph[u - 1].append(v - 1) #for i in range(N): # print(str(i) + ": ", end = "") # print(*graph[i]) # route1: 0 -> N - 2 -> N - 1 -> 0 sec1 = bfs(0, N - 2) sec2 = bfs(N - 2, N - 1) sec3 = bfs(N - 1, 0) route1 = sec1 + sec2 + sec3 if sec1 >= 0 and sec2 >= 0 and sec3 >= 0 else -1 # route2: 0 -> N - 1 -> N - 2 -> 0 sec1 = bfs(0, N - 1) sec2 = bfs(N - 1, N - 2) sec3 = bfs(N - 2, 0) route2 = sec1 + sec2 + sec3 if sec1 >= 0 and sec2 >= 0 and sec3 >= 0 else -1 if route1 >= 0 and route2 >= 0: print(min(route1, route2)) elif route1 >= 0 and route2 < 0: print(route1) elif route1 < 0 and route2 >= 0: print(route2) else: print(-1)