結果

問題 No.2316 Freight Train
ユーザー planes
提出日時 2023-05-26 21:31:48
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 393 ms / 2,000 ms
コード長 1,124 bytes
コンパイル時間 2,059 ms
コンパイル使用メモリ 171,148 KB
実行使用メモリ 7,936 KB
最終ジャッジ日時 2024-12-25 05:13:18
合計ジャッジ時間 12,359 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

  #include <bits/stdc++.h> 
using namespace std;
using ll =long long;
#define all(v) v.begin(),v.end()
 #define rep(i,a,b) for(int i=a;i<b;i++)
#define rrep(i,a,b) for(int i=a;i>=b;i--)

ll INF=2e18;

struct UnionFind {

vector<ll> par;
vector<ll> r;

void init(ll n) {
    par=vector<ll> (n);
    r=vector<ll> (n);

    for(ll i=0;i<n;i++) {
        par[i]=i;
        r[i]=0LL;
    }
}

ll find(ll x) {
    if(par[x]==x) {
        return x;
    }
    return par[x]=find(par[x]);

}

void unite(ll x,ll y) {
    x=find(x);
    y=find(y);
    if(x==y) {
        return;
    }
    if(r[x]<r[y]) {
        par[x]=y;
    }
    else {
        par[y]=x;
    if(r[x]==r[y]) {
        r[x]++;
    }
    }
}

bool same(ll x,ll y) {
    return find(x)==find(y);
}

};





int main() {
    ios::sync_with_stdio(false);
  cin.tie(0);
ll N,Q;cin>>N>>Q;
vector<ll> P(N);
for(ll i=0;i<N;i++) {
  cin>>P[i];
  if(P[i]>=0) P[i]--;
}

UnionFind p;
p.init(N);
for(ll i=0;i<N;i++) {
if(P[i]!=-1) {
  p.unite(i,P[i]);
}
}

for(ll i=0;i<Q;i++) {
  ll A,B;cin>>A>>B;
  A--;B--;
  if(p.same(A,B)) cout<<"Yes"<<endl;
  else cout<<"No"<<endl;
}
}


0