Pagini recente » Cod sursa (job #10023) | Cod sursa (job #505239) | Cod sursa (job #1504907) | Cod sursa (job #2691647) | Cod sursa (job #2977225)
#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));
}