Cod sursa(job #3297845)

Utilizator avadaravaRares Avadanei avadarava Data 23 mai 2025 21:41:50
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.94 kb
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    ifstream fin("stramosi.in");
    ofstream fout("stramosi.out");

    int N, M;
    fin >> N >> M;

    vector<int> parent(N+1);
    for(int v = 1; v <= N; v++){
        fin >> parent[v];
    }
    int LOG = 1;
    while((1 << LOG) <= N) ++LOG;

    vector<vector<int>> up(LOG, vector<int>(N+1, 0));
    for(int v = 1; v <= N; v++){
        up[0][v] = parent[v];
    }
    for(int j = 1; j < LOG; j++){
        for(int v = 1; v <= N; v++){
            int mid = up[j-1][v];
            up[j][v] = mid ? up[j-1][mid] : 0;
        }
    }
    while(M--){
        int Q, P;
        fin >> Q >> P;
        int node = Q;
        for(int j = 0; j < LOG && node; j++){
            if(P & (1 << j)){
                node = up[j][node];
            }
        }
        fout << node << "\n";
    }
    return 0;
}