Cod sursa(job #2139671)

Utilizator DawlauAndrei Blahovici Dawlau Data 22 februarie 2018 18:17:40
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.02 kb
#include<fstream>
#include<cmath>
using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
const int NMAX = 25e4 + 5, LOG2NMAX = 18;

int ancestor[LOG2NMAX][NMAX];
int nodesCount, queriesCount;

inline void readData(){

    fin >> nodesCount >> queriesCount;

    int i;
    for(i = 1; i <= nodesCount; ++i)
        fin >> ancestor[0][i];
}

inline void getAncestors(){

    int i, j;

    for(i = 1; (1 << i) <= nodesCount; ++i)
        for(j = 1; j <= nodesCount; ++j)
            ancestor[i][j] = ancestor[i - 1][ancestor[i - 1][j]];
}

inline int kthAncestor(int node, int k){

    int lg = log2(k);

    if((k & (k - 1)) == 0)
        return ancestor[lg][node];
    else
        return kthAncestor(ancestor[lg][node], k - (1 << lg));
}

inline void solveQueries(){

    int node, k;

    while(queriesCount--){

        fin >> node >> k;
        fout << kthAncestor(node, k) << '\n';
    }
}

int main(){

    readData();
    getAncestors();
    solveQueries();
}