Pagini recente » Cod sursa (job #937539) | Cod sursa (job #2486494) | Cod sursa (job #2734050) | Cod sursa (job #2184319) | Cod sursa (job #3247405)
#include <bits/stdc++.h>
using namespace std;
ifstream f("stramosi.in");
ofstream g("stramosi.out");
const int NMAX = 250005, LOGMAX = 20;
int n, m, Q, P, ancestor[LOGMAX][NMAX];
/// ancestor[i][j] = the 2^i ancestor of j
void binary_lifting()
{
for (int i = 1; i < LOGMAX; i++)
for (int j = 1; j <= n; j++)
ancestor[i][j] = ancestor[i - 1][ancestor[i - 1][j]];
}
int find_ancestor(int node, int no_ancestor)
{
if (no_ancestor >= (1 << LOGMAX))
return 0;
for (int i = 0; i < LOGMAX; i++)
if (no_ancestor & (1 << i))
node = ancestor[i][node];
return node;
}
int main()
{
f >> n >> m;
for (int i = 1; i <= n; i++)
f >> ancestor[0][i]; /// parent of i
binary_lifting();
for (int i = 1; i <= m; i++)
{
f >> Q >> P;
g << find_ancestor(Q, P) << '\n';
}
return 0;
}