【題解】CSES 1687 Company Queries I

【題目敘述】https://cses.fi/problemset/task/1687/

#include <iostream>
using namespace std;
 
int n, q, a, b, p[200005][20];
 
int main() {
    cin >> n >> q;
    for (int i = 2; i <= n; i++){
        cin >> p[i][0];
    }
    for (int i = 1; i < 20; i++){
        for (int j = 1; j <= n; j++){
            p[j][i] = p[p[j][i-1]][i-1];
        }
    }
    while (q--){
        cin >> a >> b;
        for (int i = 0; i < 20; i++){
            if (b & (1<<i)) a = p[a][i];
        }
        if (!a) cout << -1 << "\n";
        else cout << a << "\n";
    }
}
分享本文 Share with friends