結果

問題 No.2316 Freight Train
ユーザー tombo_
提出日時 2025-04-10 20:49:51
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 350 ms / 2,000 ms
コード長 2,460 bytes
コンパイル時間 1,123 ms
コンパイル使用メモリ 95,352 KB
実行使用メモリ 7,844 KB
最終ジャッジ日時 2025-04-10 20:50:04
合計ジャッジ時間 12,066 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<iostream>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<queue>
#include<set>
#include<map>
using namespace std;
#define OVERLOAD_REP(_1, _2, _3, name, ...) name
#define REP1(i, n) for (auto i = std::decay_t<decltype(n)>{}; (i) != (n); ++(i))
#define REP2(i, l, r) for (auto i = (l); (i) != (r); ++(i))
#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)
#define REP(i, l, r) rep(i, l, r+1)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
using ll = long long;
using ld = long double;
using P = pair<ll,ll>;
struct Edge {
    int to; ll w;
};
using Graph = vector<vector<int> >;
//using Graph = vector<vector<Edge> >;
const ll INF = 2e18;
//const int INF = 2e9;
template<class T> using vc = vector<T>;
template<class T> using vv = vector<vector<T> >;
template<class T> using pq = priority_queue<T>;
template<class T> using pq_g = priority_queue<T, vc<T>, greater<T> >;
template<class T> istream& operator>>(istream& i, vc<T>& v) { rep(j, 0, v.size()) i>>v[j]; return i; }
template<class T> ostream& operator<<(ostream& o, vc<T>& v) { rep(j, 0, v.size()) o<<v[j]<<" "; return o; }
template<class T> bool chmin(T& a, T b) {
    if(a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> bool chmax(T& a, T b) {
    if(a < b) {
        a = b;
        return true;
    }
    return false;
}

struct UnionFind {
    std::vector<int> par, siz;

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

    int root(int n) {
        if(par[n] == -1) return n;
        else return par[n] = root(par[n]);
    }

    bool issame(int a, int b) {
        return root(a) == root(b);
    }

    bool unite(int a, int b) {
        a = root(a); b = root(b);
        if(a == b) return false;
        if(siz[a] < siz[b]) swap(a, b);
        par[b] = a;
        siz[a] += siz[b];
        return true;
    }

    int size(int a) {
        return siz[root(a)];
    }
};
int main() {
    // 高速化
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    // 小数点の出力桁数を指定
    cout << fixed << setprecision(10);

    // メイン
    int N, Q;
    cin >> N >> Q;
    UnionFind uf(N);
    rep(i, 0, N) {
        int a; cin >> a;
        if(a != -1) uf.unite(i, a-1);
    }

    rep(i, 0, Q) {
        int a, b;
        cin >> a >> b;
        a--, b--;
        if(uf.issame(a, b)) cout << "Yes" << endl;
        else cout << "No" << endl;
    }


    return 0;
}
0