Cod sursa(job #2506708)

Utilizator vxpsnVictor Pusnei vxpsn Data 8 decembrie 2019 17:29:19
Problema Stramosi Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

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

typedef long long ll;
typedef unsigned long long ull;

const ll nmx = 250000 + 5;
const ll inf = 1<<30;
const ll MOD = 1e9 + 7;

int main() {
    ios::sync_with_stdio(0);

    in.tie(0);
    out.tie(0);

    int N, M, v[nmx], anc[nmx][18], lg[nmx], lvl[nmx];

    in>>N>>M;

    lg[2] = 1;
    for(int i = 3; i <= N + 1; ++i) {
        lg[i] = 1 + lg[i / 2];
    }


    for(int i = 1; i <= N; ++i) {
        in>>v[i];
        lvl[i] = lvl[i - 1] + 1;
        anc[i][0] = v[i];
        for(int j = 1; j <= lg[lvl[i]]; ++j) {
            anc[i][j] = anc[anc[i][j - 1]][j - 1];
        }
    }

    while(M--) {
        int P, Q;
        in>>P>>Q;
        while(1) {
            if(v[P] == 0 || Q > lvl[P] - 1) {
                out<<0<<"\n";
                break;
            }
            if(anc[P][lg[Q]] != 0 && (1 << lg[Q]) == Q) {
                out<<anc[P][lg[Q]]<<"\n";
                break;
            }
            P = anc[P][lg[Q]];
            Q -= (1<<lg[Q]);
        }
    }

    return 0;
}