CCCPaste

Untitled

#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 1e5 + 10;
int n, m;
vector graph[maxn];

int main() {
    cin >> n >> m;
    vector parent(n + 1, -1);
    for(int i = 2; i <= n; i++) {
        int x;
        cin >> x;
        parent[i] = x;
    }
    for(int i = 0; i < m; i++) {
        int x, k;
        cin >> x >> k;
        int ancestor = x;
        for(int j = 0; j < k; j++) {
            ancestor = parent[ancestor];
            if(ancestor == -1) {
                break;
            }
        }
        cout << ancestor << endl;
    }
    return 0;
}