Last active
September 15, 2023 18:57
-
-
Save NamPE286/014a048d3c78abc2c87b5394d8d664cb to your computer and use it in GitHub Desktop.
Binary Jumping (binary lifting)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://cses.fi/problemset/task/1687/ | |
#include <bits/stdc++.h> | |
using namespace std; | |
typedef long long ll; | |
ll jump(vector<vector<ll>>& parent, ll x, ll k) { | |
for(ll i = 0; i <= 18; i++) { | |
if(k & (1 << i)) { | |
x = parent[x][i]; | |
} | |
} | |
return x ?: -1; | |
} | |
void preCalc(vector<vector<ll>>& parent) { | |
for (ll k = 1; k < parent[0].size(); k++) { | |
for (ll x = 1; x < parent.size(); x++) { | |
parent[x][k] = parent[parent[x][k - 1]][k - 1]; | |
} | |
} | |
} | |
int main() { | |
ll n, q; | |
cin >> n >> q; | |
vector<vector<ll>> parent(n + 1, vector<ll>(19)); | |
for (ll i = 2; i <= n; i++) { | |
cin >> parent[i][0]; | |
} | |
preCalc(parent); | |
while (q--) { | |
ll x, k; | |
cin >> x >> k; | |
cout << jump(parent, x, k) << '\n'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment