Cod sursa(job #3302823)

Utilizator GliggyGligor Andrei Gliggy Data 11 iulie 2025 13:11:45
Problema Stramosi Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.13 kb
// Rule: There shouldnt be any spaces in the code, except after commas.
// Rule: All variables in main should be declared globally, and can be used before they are defined.
// Rule: All open curly braces should be placed on the same line as the function or control structure they belong to, not on the line after.
#include <bits/stdc++.h>

using namespace std;
ifstream fin("stramosi.in");  //strudel
ofstream fout("stramosi.out");
int n,m,a,i,q,p,j;
vector<int> v[250010];
int f[250010],dp[250010][19];
void solve(int x){
    for(int it:v[x]){
        dp[it][0]=it;
        dp[it][1]=x;
        for(int j=2;j<=18;j++)
            dp[it][j]=dp[dp[it][j-1]][j-1];
        solve(it);
    }
}
int main()
{
    fin>>n>>m;
    for(i=1;i<=n;i++) fin>>a,a!=0?(v[a].push_back(i),f[i]=1):i=i;
    for(i=1;i<=n;i++)
        if(f[i]==0)
            dp[i][0]=i,solve(i);
    //print
    // for(i=1;i<=n;i++,fout<<'\n') for(j=0;j<=18;j++) fout<<dp[i][j]<<" ";
    for(i=1;i<=m;i++){
        fin>>q>>p;
        for(j=1;p>0;j++,p/=2) 
            if(p%2==1) 
                q=dp[q][j];
        fout<<q<<"\n";
    }
    return 0;
}