Cod sursa(job #3273924)

Utilizator tudor_costinCostin Tudor tudor_costin Data 4 februarie 2025 16:13:30
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.9 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
const int Nmax=3e5;
int timer=0;
int tin[Nmax],tout[Nmax];
int up[Nmax][25];
vector<int> v[Nmax];
int p[Nmax];
void dfs(int nod,int prev)
{
    up[nod][0]=prev;
    for(int i=1;i<=19;i++)
    {
        up[nod][i]=up[up[nod][i-1]][i-1];
    }
    for(int u:v[nod])
    {
        if(u!=prev) dfs(u,nod);
    }
}
int main()
{
    int n,m;
    fin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        fin>>p[i];
        v[i].push_back(p[i]);
        v[p[i]].push_back(i);
    }
    dfs(0,0);
    for(int i=1;i<=m;i++)
    {
        int nod,q;
        fin>>nod>>q;
        for(int i=19;i>=0;i--)
        {
            if((1<<i)<=q)
            {
                nod=up[nod][i];
                q-=(1<<i);
            }
        }
        fout<<nod<<'\n';
    }
    return 0;
}