Pagini recente » Cod sursa (job #2684568) | Cod sursa (job #1972029) | Monitorul de evaluare | Cod sursa (job #1609993) | Cod sursa (job #2977237)
#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 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;
while (y)
{
int lg = int(log2(y));
x = stramos[x][lg];
y = y - (1 << lg);
}
fout << x << '\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);
}
}