Cod sursa(job #2010704)

Utilizator sfechisalin@yahoo.comSfechis Alin [email protected] Data 14 august 2017 05:39:16
Problema Stramosi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.91 kb
#include <bits/stdc++.h>

#define oo 0x3f3f3f3
using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");

int N, M;
const int LEVEL = 20;
const int L = 1 << 18;
int father[20][250005];

void precomputeSparseMatrix()
{
   for (int lev = 1; lev <= LEVEL; ++lev)
        for (int j = 1; j <= N; ++j)
            father[lev][j] = father[lev - 1][father[lev - 1][j]];
}

int query(int q, int p) {
    int step = L;
    int lg = 18;
    int pos = 0;

    for(; step; step >>= 1)
    {
        if (pos + step <= p) {
            pos += step;
            q = father[lg][q];
        }
        --lg;
    }

    return q;
}

int main()
{
    fin >> N >> M;

    for(int i = 1; i <= N; ++i)
        fin >> father[0][i];

    precomputeSparseMatrix();


    for(int P, Q; M; --M)
    {
        fin >> Q >> P;
        fout << query(Q, P) << "\n";
    }

    return 0;
}