Pagini recente » Cod sursa (job #1530635) | Cod sursa (job #2005358) | Cod sursa (job #2931453) | Cod sursa (job #2233503) | Cod sursa (job #3290646)
#include <fstream>
using namespace std;
ifstream cin("stramosi.in");
ofstream cout("stramosi.out");
int n, m;
const int LOG = 20, NMAX = 100005;
int tata[LOG][NMAX];
int depth[NMAX];
void prep(int n) {
for (int i = 1; i < LOG; i++)
for (int j = 1; j <= n; j++)
if (tata[i - 1][j])
tata[i][j] = tata[i - 1][tata[i - 1][j]];
}
int lca(int x, int y){
if (depth[x] < depth[y])
swap(x, y);
for (int i = LOG - 1; i >= 0; i--)
if (depth[x] - (1 << i) >= depth[y])
x = tata[i][x];
if (x == y) return x;
for (int i = LOG - 1; i >= 0; i--)
if(tata[i][x] && tata[i][x] != tata[i][y])
x = tata[i][x], y = tata[i][y];
return tata[0][x];
}
int deep(int x)
{
if(depth[x]) return depth[x];
if(tata[0][x]) depth[x] = 1 + deep(tata[0][x]);
else depth[x] = 0;
return depth[x];
}
int query(int p, int q)
{
if(depth[q] < p) return 0;
for (int i = LOG - 1; i >= 0; i--)
if ((1 << i) <= p && tata[i][q])
q = tata[i][q], p -= (1 << i);
return q;
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> tata[0][i];
for (int i = 1; i <= n; i++)
depth[i] = deep(i);
prep(n);
int p, q;
while (m--)
{
cin >> q >> p;
cout << query(p, q) << '\n';
}
return 0;
}