Cod sursa(job #3290646)

Utilizator mihai21681Maricutu Mihai Alexandru mihai21681 Data 31 martie 2025 14:31:44
Problema Stramosi Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.38 kb
#include <fstream>
using namespace std;
ifstream cin("stramosi.in");
ofstream cout("stramosi.out");
int n, m;
const int LOG = 20, NMAX = 100005;
int tata[LOG][NMAX];
int depth[NMAX];
void prep(int n) {
    for (int i = 1; i < LOG; i++)
        for (int j = 1; j <= n; j++)
            if (tata[i - 1][j])
                tata[i][j] = tata[i - 1][tata[i - 1][j]];
}
int lca(int x, int y){
    if (depth[x] < depth[y])
        swap(x, y);
    for (int i = LOG - 1; i >= 0; i--)
        if (depth[x] - (1 << i) >= depth[y])
            x = tata[i][x];
    if (x == y) return x;
    for (int i = LOG - 1; i >= 0; i--)
    if(tata[i][x] && tata[i][x] != tata[i][y])
        x = tata[i][x], y = tata[i][y];
    return tata[0][x];
}
int deep(int x)
{
    if(depth[x]) return depth[x];
    if(tata[0][x]) depth[x] = 1 + deep(tata[0][x]);
    else depth[x] = 0;
    return depth[x];
}
int query(int p, int q)
{
    if(depth[q] < p) return 0;
    for (int i = LOG - 1; i >= 0; i--)
        if ((1 << i) <= p && tata[i][q])
            q = tata[i][q], p -= (1 << i);
    return q;
}
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        cin >> tata[0][i];
    for (int i = 1; i <= n; i++)
        depth[i] = deep(i);
    prep(n);
    int p, q;
    while (m--)
    {
        cin >> q >> p;
        cout << query(p, q) << '\n';
    }
    return 0;
}