結果

問題 No.2565 はじめてのおつかい
ユーザー shisidor
提出日時 2023-12-02 18:02:09
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 70 ms / 2,000 ms
コード長 1,536 bytes
コンパイル時間 751 ms
コンパイル使用メモリ 81,784 KB
実行使用メモリ 9,984 KB
最終ジャッジ日時 2024-09-26 21:20:11
合計ジャッジ時間 4,415 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> G(n);
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        u--; v--;
        G[u].push_back(v);
    }
    queue<int> test;
    vector<int> dis1(n, -1), dis2(n, -1), dis3(n, -1);
    dis1[0] = 0;
    test.push(0);
    while(!test.empty()) {
        int p = test.front();
        test.pop();
        for (int w : G[p]) {
            if (dis1[w] != -1) continue;
            dis1[w] = dis1[p] + 1;
            test.push(w);
        }
    }
    dis2[n - 2] = 0;
    test.push(n - 2);
    while(!test.empty()) {
        int p = test.front();
        test.pop();
        for (int w : G[p]) {
            if (dis2[w] != -1) continue;
            dis2[w] = dis2[p] + 1;
            test.push(w);
        }
    }
    dis3[n - 1] = 0;
    test.push(n - 1);
    while(!test.empty()) {
        int p = test.front();
        test.pop();
        for (int w : G[p]) {
            if (dis3[w] != -1) continue;
            dis3[w] = dis3[p] + 1;
            test.push(w);
        }
    }
    int res = -1;
    if (dis1[n - 2] != -1 && dis2[n - 1] != -1 && dis3[0] != -1) res = dis1[n - 2] + dis2[n - 1] + dis3[0];
    if (dis1[n - 1] != -1 && dis3[n - 2] != -1 && dis2[0] != -1) {
        if (res == -1) res = dis1[n - 1] + dis3[n - 2] + dis2[0];
        else res = min(res, dis1[n - 1] + dis3[n - 2] + dis2[0]);
    }
    cout << res << endl;
    return 0;
}
0