CSES - Planet Queries I

Author: Dong Liu

Table of Contents

ExplanationImplementation

Explanation

Construct a parent matrix (where parent[i][d]\texttt{parent}[i][d] is the 2d2^dth parent of ii). Then, we can answer each query by using binary jumping from the starting node based on the binary representation of the distance.

Since the query distances can be up to 10910^9, we set the maximum depth to log2109=30\lceil{\log_2{10^9}}\rceil = 30.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N\log N)

C++

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
const int MAXD = 30; // ceil(log2(10^9))
// number of planets and queries
int n, q;
// parent matrix where [i][j] corresponds to i's (2^j)th parent
int parent[MAXN][MAXD];

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!