Company Queries I

/*
https://usaco.guide/plat/binary-jump?lang=cpp

题目链接:
https://cses.fi/problemset/task/1687

倍增法(英语:binary lifting)

这题题意是树上查找第k个祖先,
我们可以用倍增法来解决这个问题。
*/
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
int n, q;
int fa[N][20];
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> q;
    for (int i = 2; i <= n; i++) {
        cin >> fa[i][0];
    }
    // 预处理倍增表
    for (int j = 1; j < 20; j++) {
        for (int i = 1; i <= n; i++) {
            fa[i][j] = fa[fa[i][j - 1]][j - 1];
        }
    }
    while (q--) {
        int x, y;
        cin >> x >> y;
        // 二进制拆分
        for (int j = 19; j >= 0; j--) {
            if ((y >> j) & 1) {
                x = fa[x][j];
            }
        }
        if(x==0) 
            cout << -1 << endl;
        else
            cout << x << endl;
    }
    return 0;
}
posted @ 2025-04-29 10:06  katago  阅读(13)  评论(0)    收藏  举报