Cod sursa(job #2344192)

Utilizator BogdanisarBurcea Bogdan Madalin Bogdanisar Data 14 februarie 2019 21:09:04
Problema Stramosi Scor 20
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.67 kb
#include <bits/stdc++.h>

using namespace std;

#if 1
    #define pv(x) std::cerr<<#x<<" = "<<(x)<<"; ";std::cerr.flush()
    #define pn std::cerr<<std::endl
#else
    #define pv(x)
    #define pn
#endif

#ifdef INFOARENA
    ifstream in("stramosi.in");
    ofstream out("stramosi.out");
#else
    #define in cin
    #define out cout
#endif

using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
using ld = long double;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using pld = pair<ld, ld>;
#define pb push_back
const double PI = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862;
const int inf_int = 1e9 + 5;
const ll inf_ll = 1e18 + 5;
const int NMax = 25e4 + 5;
const int dx[] = {-1,0,0,+1}, dy[] = {0,-1,+1,0};
const double EPS = 1e-8;

int depth[NMax], ancestor[NMax][20];
vector<int> adj[NMax];

int getAncestor(int node, int pth, int N) {
    if (pth >= N) {
        return 0;
    }

    for (int e = 20; e >= 0; --e) {
        if ((1<<e) <= pth) {
            node = ancestor[node][e];
            pth -= (1<<e);
        }
    }

    return node;
}

int main() {
    cin.sync_with_stdio(false);
    cin.tie(0);

    int N,M;
    in >> N >> M;
    for (int i = 1; i <= N; ++i) {
        int dad;
        in >> dad;

        adj[dad].pb(i);
        depth[i] = depth[dad] + 1;
        ancestor[i][0] = dad;
    }

    for (int pw = 1; (1<<pw) <= N; pw <<= 1) {
        for (int i = 1; i <= N; ++i) {
            ancestor[i][pw] = ancestor[ ancestor[i][pw - 1] ][pw - 1];
        }
    }

    for (int i = 1; i <= M; ++i) {
        int q,p;
        in >> q >> p;

        out << getAncestor(q, p, N) << '\n';
    }

    return 0;
}