結果
問題 | No.2565 はじめてのおつかい |
ユーザー | Mikan04y |
提出日時 | 2023-12-02 16:59:30 |
言語 | C++17(gcc12) (gcc 12.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 90 ms / 2,000 ms |
コード長 | 1,996 bytes |
コンパイル時間 | 2,292 ms |
コンパイル使用メモリ | 208,732 KB |
実行使用メモリ | 9,088 KB |
最終ジャッジ日時 | 2024-09-26 20:58:23 |
合計ジャッジ時間 | 6,392 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 50 |
ソースコード
#include <bits/stdc++.h> using namespace std; const int MAX_N = 100'009; int N; int visited[MAX_N]; void v_clear() { for (int i = 0; i < N; i++) visited[i] = -1; } void bfs(vector<vector<int>> &Graph, queue<int> &Q, int first) { v_clear(); visited[first] = 0; Q.push(first); while (!Q.empty()) { int place = Q.front(); Q.pop(); for (int next : Graph[place]) { if (visited[next] != -1) continue; visited[next] = visited[place] + 1; Q.push(next); } } } int main() { int M; cin >> N >> M; vector<vector<int>> Graph(N, vector<int>(0)); for (int i = 0; i < M; i++) { int u, v; cin >> u >> v; u--, v--; Graph[u].push_back(v); } queue<int> Q; int len1toN, len1toN_bfr, lenN_bfrto1, lenN_bfrtoN, lenNto1, lenNtoN_bfr; // 1 -> N-1, 1 -> N bfs(Graph, Q, 0); len1toN = visited[N - 1]; len1toN_bfr = visited[N - 2]; // N-1 -> 1, N-1 -> N bfs(Graph, Q, N - 2); lenN_bfrto1 = visited[0]; lenN_bfrtoN = visited[N-1]; // N -> 1, N -> N-1 bfs(Graph, Q, N - 1); lenNto1 = visited[0]; lenNtoN_bfr = visited[N - 2]; // cout << len1toN << endl; // cout << len1toN_bfr << endl; // cout << lenN_bfrto1 << endl; // cout << lenN_bfrtoN << endl; // cout << lenNto1 << endl; // cout << lenNtoN_bfr << endl; int path1, path2; if (len1toN_bfr == -1 || lenN_bfrtoN == -1 || lenNto1 == -1) path1 = -1; else path1 = len1toN_bfr + lenN_bfrtoN + lenNto1; if (len1toN == -1 || lenNtoN_bfr == -1 || lenN_bfrto1 == -1) path2 = -1; else path2 = len1toN + lenNtoN_bfr + lenN_bfrto1; if (path1 == -1 && path2 == -1) cout << -1 << endl; else if (path1 == -1) cout << path2 << endl; else if (path2 == -1) cout << path1 << endl; else cout << min(path1, path2) << endl; }