Cod sursa(job #2010700)

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

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

int N, M, H = -oo, LEVEL;
vector<vector<int>>father;

int height()
{
    int answ = -oo, cnt;

    for (int i = 1; i <= N; ++i)
    {
        cnt = 0;
        for (int j = i; father[j][0]; ++cnt, j = father[j][0]);
        answ = max(answ, cnt);
    }
    return answ;
}

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

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

     father.resize(N + 1, vector<int>(N + 1, 0));

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

    H = height();

    for(; (1 << LEVEL) < H; ++LEVEL);

    precomputeSparseMatrix();


    for(int P, Q; M; --M)
    {
        fin >> Q >> P;

        for (int i = 0; (1 << i) <= P; ++i)
            if (P & (1 << i))
                Q = father[Q][i];

        fout << Q << "\n";
    }

    return 0;
}