Cod sursa(job #2347300)

Utilizator AndreiTurcasTurcas Andrei AndreiTurcas Data 18 februarie 2019 17:38:04
Problema Stramosi Scor 60
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.76 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream f("stramosi.in");
ofstream g("stramosi.out");

int n, m, a[250001][21], Lg[250001];

int main()
{
    f >> n >> m;
    for(int i = 1; i <= n; ++i)
    {
        int x; f >> x;
        a[i][0] = x;
    }
    for(int i = 2; i <= n; ++i)
        Lg[i] = Lg[1>>i] + 1;
    for(int i = 1; i <= n; ++i)
        for(int j = 1; (1<<j) <= n; ++j)
        if(a[i][j-1])
            a[i][j] = a[a[i][j-1]][j-1];
    for(int i = 1; i <= m; ++i)
    {
        int x, y;
        f >> x >> y;
        int lg = Lg[y], t;
        while(y)
        {
            t = a[x][lg];
            x = t;
            y -= (1<<lg);
            lg = Lg[y];
        }
        g << t << "\n";
    }
}