Cod sursa(job #1288839)

Utilizator RaduVisanRadu Visan RaduVisan Data 9 decembrie 2014 08:51:14
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.65 kb
#include <cstdio>
using namespace std;

const int NMAX = 250010;

int N, M, Ancestor[19][NMAX], P, Q;

int main()
{
    freopen("stramosi.in", "r", stdin);
    freopen("stramosi.out", "w", stdout);

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

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

    for(; M; M --)
    {
        scanf("%i %i", &Q, &P);

        for(int i = 0; i <= 18; ++ i)
            if(P & (1 << i))
                Q = Ancestor[i][Q];

        printf("%i\n", Q);
    }
}