結果

問題 No.2316 Freight Train
ユーザー tikutikuwa
提出日時 2023-05-26 22:12:20
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 94 ms / 2,000 ms
コード長 1,179 bytes
コンパイル時間 1,990 ms
コンパイル使用メモリ 170,060 KB
実行使用メモリ 5,248 KB
最終ジャッジ日時 2024-12-25 07:23:41
合計ジャッジ時間 7,089 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i < (int)(n + 1); i++)
using ll = long long;
using Graph = vector<vector<int>>;

struct UnionFind {
    vector<int> par;

    UnionFind(int n) : par(n, -1) {}

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

    void unite(int x, int y) {
        x = root(x);
        y = root(y);
        if (x != y) {
            if (par[y] < par[x]) swap(x, y);
            par[x] += par[y];
            par[y] = x;
        }
    }

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

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int N, Q;
    cin >> N >> Q;
    vector<int> P(N);
    for (int i = 0; i < N; i++) {
        cin >> P[i];
        P[i]--;
    }

    UnionFind uf(N);
    for (int i = 0; i < N; i++) {
        if (P[i] != -2) uf.unite(i, P[i]);
    }

    while (Q--) {
        int A, B;
        cin >> A >> B;
        A--; B--;
        if (uf.same(A, B)) cout << "Yes" << "\n";
        else cout << "No" << "\n";
    }

    return 0;
}
0