The official problem title is Planets Queries I. Its functional-graph successor queries match the code's binary lifting table and kth-successor answers.
Graphs & trees
Problem and code
Useful links.
Written by benbenyaojifen. Try the problem first, then compare your approach with the code.
1#include<bits/stdc++.h>2usingnamespace std; //❄️ idea is to use binary lifting to precompute the jumps(how many teleport)3intmain(){4 ios::sync_with_stdio(0); cin.tie(0);5int n, q; cin >> n >> q;6constintMM=30; // cuz 2 ^ 30 > k(1e9)7vector<vector<int>>jump(MM, vector<int>(n +1));8for(int i =1; i <= n; i++){9int t; cin >> t;10 jump[0][i] = t; // jump[i][j] = the planet you reach if you start at j and take 2^i teleports.11 }12for(int i =1; i <MM; i++){13for(int j =1; j <= n; j++){14 jump[i][j] = jump[i -1][jump[i -1][j]];15 }16 }17while(q--){18int x; longlong y; cin >> x >> y;19for(int i =0; i <MM; i++){20if((y >> i) & 1LL) x = jump[i][x];21 }22 cout << x <<'\n';23 }24return0;25}
☕
Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.
Python records executed lines and locals automatically. For selected values in any language, add // @trace i, total on its own valid line; Python uses # @trace i, total.
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.
Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.