Cod sursa(job #1706419)

Utilizator cristian.caldareaCaldarea Cristian Daniel cristian.caldarea Data 22 mai 2016 16:12:06
Problema Stramosi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.88 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

const int Nmax = 250002;

int n, m;
int log2[20], s[Nmax][20];


int main()
{
    int x, y;
    fin >> n >> m;

    for ( int i = 1; i <= n; i++ )
    {
        fin >> x;
        if (x)
        {
            s[i][0] = x;
        }
    }

    log2[1] = 0;
    for ( int i = 2; i < 20; i++ )
        log2[i] = log2[i/2] + 1;


    for ( int j = 0; j <= log2[n]; j++ )
        for ( int i = 1; i <= n; i++ )
            s[i][j+1] = s[s[i][j]][j];

    while(m)
    {
        m--;
        fin >> x >> y;
        while(y > 0)
        {
            x = s[x][log2[y]];
            y = y - (1 << log2[y]);
            if ( x == 0 )
                break;
        }
        fout << x << '\n';
    }

    return 0;
}