CSES Solutions
#1750Graph Algorithms

Planets Queries I

View on CSES

Solution

1750-Planets_Queries_I.cpp
1#include<bits/stdc++.h>
2using namespace std;
3#define int long long
4signed main(){
5  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
6  int n,q; cin>>n>>q;
7  int pa[n][32];
8  for(int i=0;i<n;++i){
9    cin>>pa[i][0];
10    --pa[i][0];
11  }
12  for(int j=0;j<31;++j) for(int i=0;i<n;++i)
13    pa[i][j+1]=pa[pa[i][j]][j];
14  while(q--){
15    int x,k; cin>>x>>k; --x;
16    for(int i=0;i<32;++i) if(k>>i&1){
17      x=pa[x][i];
18    }
19    cout<<x+1<<'\n';
20  }
21  return 0;
22}

Editorial not yet generated for this problem. Run the editorial generation script to add hints and detailed explanations.