CSES · 1750

Planets Queries I

This C++ solution uses binary lifting for CSES 1750 Planets Queries I. Read the reasoning, inspect the code, or try your own test case below.

1750Graphs & treesBinary liftingC++25 lines
Solution030of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Binary lifting

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.

Open official problem ↗View exact source file ↗
Implementation

binary_lifting.cpp

C++

    #include<bits/stdc++.h>
    using namespace std; //❄️ idea is to use binary lifting to precompute the jumps(how many teleport)
    int main(){
        ios::sync_with_stdio(0); cin.tie(0);
        int n, q; cin >> n >> q;
        const int MM = 30; // cuz 2 ^ 30 > k(1e9)
        vector<vector<int>> jump(MM, vector<int>(n + 1));
        for(int i = 1; i <= n; i++){
            int t; cin >> t;
            jump[0][i] = t; // jump[i][j] = the planet you reach if you start at j and take 2^i teleports.
        }
        for(int i = 1; i < MM; i++){
            for(int j = 1; j <= n; j++){
                jump[i][j] = jump[i - 1][jump[i - 1][j]];
            }
        }
        while(q--){
            int x; long long y; cin >> x >> y;
            for(int i = 0; i < MM; i++){
                if((y >> i) & 1LL) x = jump[i][x];
            }
            cout << x << '\n';
        }
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
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.