結果

問題 No.2565 はじめてのおつかい
ユーザー hatsuka_iwa
提出日時 2023-12-14 22:52:13
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 89 ms / 2,000 ms
コード長 779 bytes
コンパイル時間 2,069 ms
コンパイル使用メモリ 201,996 KB
最終ジャッジ日時 2025-02-18 11:01:17
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

int main() {
  int N, M, INF = 1e8; cin >> N >> M;
  vector<int> A, B, C;
  vector<vector<int>> G(N);

  for (int i = 0; i < M; i++) {
    int u, v; cin >> u >> v;
    G.at(u - 1).push_back(v - 1);
  }

  auto BFS = [&](int x) {
    vector<int> dist(N, INF);
    queue<int> Q;
    
    dist.at(x) = 0;
    Q.push(x);

    while (!Q.empty()){
      int v = Q.front();
      Q.pop();

      for (int to : G.at(v)) {
        if (dist.at(to) != 1e8) continue;
        dist.at(to) = dist.at(v) + 1;
        Q.push(to);
      }
    }

    return dist;
  };

  A = BFS(0); B = BFS(N - 2); C = BFS(N - 1);
  int Ans = min(A.at(N - 2) + B.at(N - 1) + C.at(0), A.at(N - 1) + C.at(N - 2) + B.at(0));
  cout << (Ans < INF ? Ans : -1) << endl;
}
0