CSES Solutions
#1687Tree Algorithms

Company Queries I

View on CSES

Solution

1687-Company_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+1][18]; pa[0][0] = pa[1][0] = 0;
8  for(int i=2; i<=n; ++i) {
9    cin>>pa[i][0];
10  }
11  for(int j=0; j<17; ++j) for(int i=0; i<=n; ++i)
12    pa[i][j+1] = pa[pa[i][j]][j];
13
14  while(q--) {
15    int x,k; cin>>x>>k;
16    int ans=x;
17    for(int j=0; j<18; ++j) if(k>>j&1)
18      ans=pa[ans][j];
19    cout<<(ans?ans:-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.