Cod sursa(job #2977225)

Utilizator Iordache_CezarIordache Cezar Iordache_Cezar Data 11 februarie 2023 09:41:56
Problema Stramosi Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.16 kb
#include <bits/stdc++.h>
#define NMAX 250008

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

int n, m, stramos[NMAX][20], nivel[NMAX];
vector <int> G[NMAX];

void DFS(int nod);
int query(int nod, int p);

int main()
{
    int x, y;
    fin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        fin >> x;
        G[x].push_back(i);
        stramos[i][0] = x;
    }
    for (int i = 1; i <= n; i++)
        if (stramos[i][0] == 0)
            DFS(i);
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        fout << query(x, y) << "\n";
    }
    return 0;
}

void DFS(int nod)
{
    for (auto el : G[nod])
        if (nivel[el] == 0)
        {
            nivel[el] = nivel[nod] + 1;
            stramos[el][0] = nod;
            for (int j = 1; (1 << j) < nivel[el]; j++)
            {
                stramos[el][j] = stramos[stramos[el][j-1]][j-1];
            }
            DFS(el);
        }
}

int query(int nod, int p)
{
    if (p == 0)
        return nod;
    if (p == 1)
        return stramos[nod][0];
    int x = (int)(log2(p));
    query(stramos[nod][x], p-(1<<x));
}