Cod sursa(job #1257622)

Utilizator japjappedulapPotra Vlad japjappedulap Data 7 noiembrie 2014 23:12:12
Problema Stramosi Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.94 kb
#include <fstream>
#include <vector>
#include <bitset>
using namespace std;

#define NZ 250004

ifstream is ("stramosi.in");
ofstream os ("stramosi.out");

int N, M, stk[NZ], K;
vector <int> G[NZ], Q[NZ];
bitset <NZ> B, root;

void DFS(int t);

int main()
{
    is >> N >> M;
    for (int i = 1, a; i <= N; ++i)
    {
        is >> a;
        if (a == 0) root[i] = 1;
        else G[a].push_back(i);
    }
    for (int i = 1; i <= N; ++i)
        if (root[i])
            DFS(i);

    for (int i = 1, nod; i <= M; ++i)
    {
        is >> nod >> K;
        if (Q[nod].size() <= K)  os << "0\n";
        else os << Q[nod][K] << '\n';
    }
    is.close();
    os.close();
}

void DFS(int t)
{
    B[t] = 1;
    stk[++K] = t;
    for (int j = K; j > 0; --j)
        Q[t].push_back(stk[j]);
    for (const auto& f : G[t])
        if (B[f] == 0)
            DFS(f);
    --K;
};