結果
問題 | No.2565 はじめてのおつかい |
ユーザー |
|
提出日時 | 2023-12-02 15:49:52 |
言語 | D (dmd 2.109.1) |
結果 |
AC
|
実行時間 | 166 ms / 2,000 ms |
コード長 | 1,657 bytes |
コンパイル時間 | 4,225 ms |
コンパイル使用メモリ | 174,604 KB |
実行使用メモリ | 13,056 KB |
最終ジャッジ日時 | 2024-09-26 19:22:25 |
合計ジャッジ時間 | 9,164 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 50 |
ソースコード
import std; void main () { int N, M; readln.read(N, M); int[][] graph = new int[][](N, 0); foreach (i; 0..M) { int u, v; readln.read(u, v); u--, v--; graph[u] ~= v; } solve(N, M, graph); } void solve (int N, int M, int[][] graph) { /* 最適ルートは 1 -> N-1 -> N -> 1 or 1 -> N -> N-1 -> 1のどちらか。これを全部BFSで調べる */ int[] visited = new int[](N); DList!int Q; void BFS (int begin) { visited[] = int.max; visited[begin] = 0; Q.insertBack(begin); while (!Q.empty) { auto head = Q.front; Q.removeFront; foreach (to; graph[head]) { if (visited[to] == int.max) { visited[to] = visited[head] + 1; Q.insertBack(to); } } } } int ans = int.max; { // 1 -> N-1 -> N -> 1 long candi = 0; BFS(0); candi += visited[N-2]; BFS(N-2); candi += visited[N-1]; BFS(N-1); candi += visited[0]; if (candi < int.max) ans = min(ans, cast(int) candi); } { // 1 -> N -> N-1 -> 1 long candi = 0; BFS(0); candi += visited[N-1]; BFS(N-1); candi += visited[N-2]; BFS(N-2); candi += visited[0]; if (candi < int.max) ans = min(ans, cast(int) candi); } if (ans == int.max) { writeln(-1); } else { writeln(ans); } } void read (T...) (string S, ref T args) { auto buf = S.split; foreach (i, ref arg; args) { arg = buf[i].to!(typeof(arg)); } }