Cod sursa(job #2862105)

Utilizator gripzStroescu Matei Alexandru gripz Data 4 martie 2022 21:26:27
Problema Stramosi Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.85 kb
#include <fstream>

#define NMAX 250003
#define LOG 18

using namespace std;

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

int N, M;
int Fathers[NMAX];
int up[NMAX][LOG];


int main()
{

    fin >> N >> M;
    for(int i = 1; i <= N; i++) {
        int f;
        fin >> f;
        Fathers[i] = f;
    }

    for(int i = 1; i <= N; i++) {
        up[i][0] = Fathers[i];
    }

    for(int j = 1; j < LOG; j++) {
        for(int i = 1; i <= N; i++) {
            up[i][j] = up[up[i][j - 1]][j - 1];
        }
    }

    for(int i = 1; i <= M; i++) {
        int nod, nr;
        fin >> nod >> nr;
        int sol = 0;
        while(nr > 0) {
            if(nr % 2 == 1)
                nod = up[nod][sol];
            sol++;
            nr /= 2;
        }
        fout << nod << '\n';
    }


    return 0;
}