結果
| 問題 | No.2565 はじめてのおつかい | 
| コンテスト | |
| ユーザー |  srjywrdnprkt | 
| 提出日時 | 2023-12-07 14:39:05 | 
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 46 ms / 2,000 ms | 
| コード長 | 973 bytes | 
| コンパイル時間 | 2,047 ms | 
| コンパイル使用メモリ | 203,788 KB | 
| 最終ジャッジ日時 | 2025-02-18 08:57:44 | 
| ジャッジサーバーID (参考情報) | judge5 / judge5 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 50 | 
ソースコード
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
vector<ll> bfs(vector<vector<int>> &E, int start){
    int N = E.size();
    int from, to;
    queue<int> que;
    vector<ll> dist(N, 1e9);
    dist[start] = 0;
    que.push(start);
    while(!que.empty()){
        from = que.front();
        que.pop();
        for (auto to : E[from]){
            if (dist[to] != 1e9) continue;
            dist[to] = dist[from] + 1;
            que.push(to);
        }
    }
    return dist;
}
int main(){
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    int N, M, A, B;
    ll ans;
    cin >> N >> M;
    vector<vector<int>> E(N);
    for (int i=0; i<M; i++){
        cin >> A >> B; A--; B--;
        E[A].push_back(B);
    }
    vector<ll> dist1 = bfs(E, 0), dist2 = bfs(E, N-2), dist3 = bfs(E, N-1);
    ans = min(dist1[N-2]+dist2[N-1]+dist3[0], dist1[N-1]+dist3[N-2]+dist2[0]);
    cout << (ans < 1e9 ? ans : -1) << endl;
    return 0;
}
            
            
            
        