Cod sursa(job #2010842)

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

using namespace std;
const int LEVEL = 20;

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

int N, M;
vector<vector<int>>father;

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

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

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

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

    precomputeSparseMatrix();

    for(int P, Q; M; --M)
    {
        fin >> Q >> P;
        for (int i = 0; (1 << i) <= P; ++i)
            if (P & (1 << i))
                Q = father[i][Q];
        fout << Q << "\n";
    }

    return 0;
}