Cod sursa(job #2596673)

Utilizator sichetpaulSichet Paul sichetpaul Data 10 aprilie 2020 10:57:46
Problema Stramosi Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.71 kb
#include <bits/stdc++.h>
#define Nmax 250005
#define LG 20
using namespace std;

int N, Q, L, root;
int anc[Nmax][LG];

int solve(int x, int y) {
    for (int i = L; i >= 0; --i)
        if ((1 << i) & y) x = anc[x][i];
    return x;
}
int main()
{
    freopen("stramosi.in", "r", stdin);
    freopen("stramosi.out", "w", stdout);
    scanf("%d%d", &N, &Q);
    L = ceil(log2(N));

    for (int i = 1; i <= N; ++i)
        scanf("%d", &anc[i][0]);

    for (int j = 1; j <= L; ++j)
    for (int i = 1; i <= N; ++i)
        anc[i][j] = anc[anc[i][j - 1]][j - 1];

    while (Q--) {
        int x, y;
        scanf("%d%d", &x, &y);
        printf("%d\n", solve(x, y));
    }

    return 0;
}