Cod sursa(job #1761463)

Utilizator preda.andreiPreda Andrei preda.andrei Data 22 septembrie 2016 12:13:27
Problema Stramosi Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.98 kb
#include <fstream>
#include <iostream>

using namespace std;

const int kNmax = 250010;
const int kLogN = 18;

int tata[kLogN][kNmax];

int AflaStramos(int nod, int k)
{
    int stramos = nod;
    int put = 0;

    while ((1 << put) <= k)
        ++put;
    --put;

    while (k > 0 && stramos > 0) {
        stramos = tata[put][stramos];
        k -= (1 << put);
        while ((1 << put) > k)
            --put;
    }

    return stramos;
}

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

    int n, m;
    fin >> n >> m;

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

        int poz = tata[0][i];
        int put = 1;

        while (poz > 0) {
            tata[put][i] = tata[put - 1][poz];
            poz = tata[put - 1][poz];
            ++put;
        }
    }

    while (m--) {
        int x, y;
        fin >> x >> y;
        fout << AflaStramos(x, y) << "\n";
    }

    return 0;
}