結果
| 問題 | No.2565 はじめてのおつかい | 
| コンテスト | |
| ユーザー |  toshiconner | 
| 提出日時 | 2023-12-02 15:58:28 | 
| 言語 | C++23 (gcc 13.3.0 + boost 1.87.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 89 ms / 2,000 ms | 
| コード長 | 1,259 bytes | 
| コンパイル時間 | 1,219 ms | 
| コンパイル使用メモリ | 114,388 KB | 
| 実行使用メモリ | 11,776 KB | 
| 最終ジャッジ日時 | 2024-09-26 19:37:08 | 
| 合計ジャッジ時間 | 5,284 ms | 
| ジャッジサーバーID (参考情報) | judge2 / judge4 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 50 | 
ソースコード
#include<iostream>
#include<vector>
#include<ranges>
#include<queue>
using namespace std;
using ll = long long;
using Graph = vector<vector<int>>;
void bfs(Graph& G, int start, vector<ll>& dist) {
    dist[start] = 0;
    ll inf = 1e12;
    queue<int> que;
    que.push(start);
    while (!que.empty()) {
        auto cur_v = que.front();
        que.pop();
        for (auto next_v : G[cur_v]) {
            if (dist[next_v] != inf) {
                continue;
            }
            que.push(next_v);
            dist[next_v] = dist[cur_v] + 1;
        }
    }
}
int main() {
    int N, M; cin >> N >> M;
    Graph G(N);
    for(int i = 0; i < M; ++i) {
        int u, v; cin >> u >> v; u--; v--;
        G[u].push_back(v);
    }
    ll inf = 1e12;
    // 0 -> N - 1
    // N - 1 -> N
    // N -> 0
    // 0 -> N
    // N -> N - 1
    // N - 1 -> 0
    vector<vector<ll>> dists(3, vector(N, inf));
    bfs(G, 0, dists[0]);
    bfs(G, N - 2, dists[1]);
    bfs(G, N - 1, dists[2]);
    auto ans1 = dists[0][N - 2] + dists[1][N - 1] + dists[2][0];
    auto ans2 = dists[0][N - 1] + dists[2][N - 2] + dists[1][0];
    auto ans = min(ans1, ans2);
    if (ans >= inf) {
        cout << -1 << endl;
    } else {
        cout << ans << endl;
    }
}
            
            
            
        