結果

問題 No.2316 Freight Train
ユーザー srjywrdnprktsrjywrdnprkt
提出日時 2023-05-26 21:29:25
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 448 ms / 2,000 ms
コード長 1,378 bytes
コンパイル時間 994 ms
コンパイル使用メモリ 107,492 KB
実行使用メモリ 4,844 KB
最終ジャッジ日時 2023-08-26 10:21:23
合計ジャッジ時間 12,819 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 434 ms
4,564 KB
testcase_04 AC 237 ms
4,376 KB
testcase_05 AC 166 ms
4,376 KB
testcase_06 AC 55 ms
4,376 KB
testcase_07 AC 370 ms
4,380 KB
testcase_08 AC 254 ms
4,692 KB
testcase_09 AC 322 ms
4,380 KB
testcase_10 AC 348 ms
4,380 KB
testcase_11 AC 303 ms
4,420 KB
testcase_12 AC 371 ms
4,380 KB
testcase_13 AC 443 ms
4,696 KB
testcase_14 AC 444 ms
4,656 KB
testcase_15 AC 445 ms
4,544 KB
testcase_16 AC 448 ms
4,540 KB
testcase_17 AC 441 ms
4,700 KB
testcase_18 AC 442 ms
4,632 KB
testcase_19 AC 444 ms
4,532 KB
testcase_20 AC 443 ms
4,696 KB
testcase_21 AC 446 ms
4,684 KB
testcase_22 AC 442 ms
4,696 KB
testcase_23 AC 411 ms
4,844 KB
testcase_24 AC 430 ms
4,608 KB
testcase_25 AC 415 ms
4,532 KB
testcase_26 AC 406 ms
4,628 KB
testcase_27 AC 313 ms
4,380 KB
testcase_28 AC 2 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <queue>
#include <algorithm>
#include <numeric>
#include <deque>

using namespace std;
using ll = long long;

struct UnionFind {
    int ngroup;
    vector<int> par;
    vector<int> siz;

    UnionFind(int N) : par(N), siz(N) {
        ngroup = N;
        for(int i = 0; i < N; i++){
            par[i] = i;
            siz[i] = 1;
        }
    }

    int root(int x) {
        if (par[x] == x) return x;
        return par[x] = root(par[x]);
    }

    int unite(int x, int y) {
        int rx = root(x);
        int ry = root(y);
        if (rx == ry) return rx;
        ngroup--;
        if (siz[rx] > siz[ry]) swap(rx, ry);
        par[rx] = ry;
        siz[ry] += siz[rx];
        return ry;
    }

    bool same(int x, int y) {
        int rx = root(x);
        int ry = root(y);
        return rx == ry;
    }

    int size(int x){
        return siz[root(x)];
    }

    int group_count(){
        return ngroup;
    }
};

int main(){
 
    int N, Q, P, A, B;
    cin >> N >> Q;
    UnionFind tree(N+1);

    for (int i=1; i<=N; i++){
        cin >> P;
        if (P == -1) continue;
        else tree.unite(i, P);
    }

    for (int i=0; i<Q; i++){
        cin >> A >> B;
        cout << (tree.same(A, B) ? "Yes" : "No") << endl;
    }
 
    return 0;
}
0