Cod sursa(job #2810440)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 29 noiembrie 2021 14:40:52
Problema Stramosi Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.91 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

#pragma GCC optimize ("Ofast")

const int maxN = 255005, maxLg = 19;
int n, nq;
int s[maxN][maxLg + 5];
vector <int> G[maxN];

void dfs(int nod)
{
    for(int i = 1; i <= maxLg; i++)
        s[nod][i] = s[s[nod][i - 1]][i - 1];
    for(int i = 0; i < (int) G[nod].size(); i++)
        dfs(G[nod][i]);
}

int main()
{
    ios::sync_with_stdio(false);
    fin >> n >> nq;
    for(int i = 1; i <= n; i++)
    {
        int t;
        fin >> t;
        G[t].push_back(i);
        s[i][0] = t;
    }
    dfs(0);
    for(int i = 1; i <= nq; i++)
    {
        int nod, nr;
        fin >> nod >> nr;
        for(int j = maxLg; j >= 0; j--)
            if(nr & (1 << j))
                nod = s[nod][j];
        fout << nod << '\n';
    }
    return 0;
}