Cod sursa(job #2894802)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 28 aprilie 2022 13:32:04
Problema Stramosi Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.87 kb
/// [A][M][C][B][N] ///
#include <bits/stdc++.h>
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
typedef long long ll;
using namespace std;

class InParser {
private:
    FILE *fin;
    char *buff;
    int sp;
    char read_ch() {
        if (++sp == 4096) {
            sp = 0, fread(buff, 1, 4096, fin);
        }
        return buff[sp];
    }
public:
    InParser(const char* name) {
        fin = fopen(name, "r");
        buff = new char[4096]();
        sp = 4095;
    }
    template<typename T>
    InParser& operator >> (T &number) {
        register T ch, sgn = 1;
        number = 0;
        while (!isdigit(ch = read_ch()) && ch != '-');
        if (ch == '-') {
            sgn = -1, ch = read_ch();
        }
        do {
            number = 10 * number + ch - '0';
        } while (isdigit(ch = read_ch()));
        number *= sgn;
        return *this;
    }
} fin("stramosi.in");
ofstream fout("stramosi.out");

namespace kth_ancestor {
    vector<vector<int>> t;
    // t[i][j] = 2^i'th ancestor of node j
    void build(int n, vector<int>& root) {
        t.assign(log2(n) + 1, vector<int>(n + 2));
        for (int i = 1; i <= n; ++i) {
            t[0][i] = root[i];
        }
        for (int i = 1; (1 << i) <= n; ++i) {
            for (int j = 1; j <= n; ++j) {
                t[i][j] = t[i - 1][t[i - 1][j]];
            }
        }
    }
    int querry(int i, int k) {
        for (int j = 0; (1 << j) <= k; ++j) {
            if ((k >> j) & 1) {
                i = t[j][i];
            }
        }
        return i;
    }
}

int main() {
    int n, q;
    fin >> n >> q;
    vector<int> v(n + 2);
    for (int i = 1; i <= n; ++i) {
        fin >> v[i];
    }
    kth_ancestor::build(n, v);
    while (q--) {
        int i, k;
        fin >> i >> k;
        fout << kth_ancestor::querry(i, k) << nl;
    }
}