Cod sursa(job #2714375)

Utilizator VladTZYVlad Tiganila VladTZY Data 1 martie 2021 18:47:54
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.03 kb
#include <fstream>
#include <math.h>
#include <string.h>

#define NMAX 250005
#define LOGMAX 20

using namespace std;

ifstream f("stramosi.in");
ofstream g("stramosi.out");

int n, questions, father, node, kth;
int LOG;
int dp[NMAX][LOGMAX];

void addToParse(int node, int root) {
    dp[node][0] = root;

    for (int i = 1; i <= LOG; i++) {
        dp[node][i] = dp[dp[node][i - 1]][i - 1];

        if (dp[node][i] == 0)
            return;
    }
}

int kThAncestor(int node, int level) {

    for (int i = 0; i <= LOG; i++) {

        if (level & (1 << i)) {
            node = dp[node][i];

            if (node == -1)
                return 0;
        }
    }

    return node;
}

int main()
{
    f >> n >> questions;

    LOG = (int)ceil(log2(n));

    for (int i = 1; i <= n; i++) {
        f >> father;

        addToParse(i, father);
    }

    for (int i = 1; i <= questions; i++) {
        f >> node >> kth;

        g << kThAncestor(node, kth) << "\n";
    }

    return 0;
}