Cod sursa(job #3221925)

Utilizator alex_0747Gheorghica Alexandru alex_0747 Data 8 aprilie 2024 16:12:08
Problema Stramosi Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.89 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
using namespace std;

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

vector <int> L[100005], ancestor[100005], roots;// bloody roots
int n;

void DFS(int k)
{
    for (int i : L[k])
    {
        for (int j : ancestor[k])
            ancestor[i].push_back(j);
        ancestor[i].push_back(k);
        DFS(i);
    }
}

int main()
{
    int i, q, x, t;
    fin >> n >> q;
    for (i = 1; i <= n; i++)
    {
        fin >> t;
        if (t == 0)
            roots.push_back(i);
        else
            L[t].push_back(i);
    }

    for (int i : roots)
        DFS(i);

    while (q--)
    {
        fin >> x >> t;
        if (ancestor[x].size() < t)
            fout << "0\n";
        else
            fout << ancestor[x][ancestor[x].size() - t] << "\n";
    }
    return 0;
}