Cod sursa(job #3295804)

Utilizator code_blocksSpiridon Mihnea-Andrei code_blocks Data 8 mai 2025 15:29:52
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.72 kb
#include <iostream>
#include <fstream>
#include <cmath>

#define BUF_SIZE 250001
#define POW_SIZE 21

using namespace std;

int p[BUF_SIZE + 1][POW_SIZE];
int n, q;

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

void build()
{
    for(int j = 1; j <= int(log2(n)); j++)
        for(int i = 1; i <= n; i++)
            p[i][j] = p[p[i][j - 1]][j - 1];
}

int query(int x, int d)
{
    for(int i = 0; (1 << i) <= d; i++)
        if(d & (1 << i))
            x = p[x][i];

    return x;
}

int main() 
{
    fin >> n >> q;
    for(int i = 1; i <= n; i++) 
        fin >> p[i][0];

    build();

    for(int i = 1; i <= q; i++)
    {
        int x, d;
        fin >> x >> d;
        fout << query(x, d) << '\n';
    }

	return 0;
}