Pagini recente » Cod sursa (job #552034) | Cod sursa (job #1264950) | Cod sursa (job #2547538) | Cod sursa (job #1268401) | Cod sursa (job #2608068)
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int N = 100001;
const int M = 100001;
const int L = 18;
int n, m, nr, time1, vf[N], urm[N], lst[N], t[L][N], tb[N], to[N];
void add(int x, int y)
{
vf[++nr] = y;
urm[nr] = lst[x];
lst[x] = nr;
}
void dfs(int x)
{
tb[x] = ++time1;
int y;
for (int p = lst[x]; p != 0; p = urm[p])
{
y = vf[p];
if (tb[y] == 0)
{
dfs(y);
t[0][y] = x;
}
}
to[x] = ++time1;
}
int lca(int x, int y)
{
if(tb[x]<=tb[y] && to[y]<=to[x])
{
return x;
}
int pas = L - 1;
int s;
while (pas >= 0)
{
s = t[pas][x];
if (s != 0 && ((tb[s] > tb[y]) || (to[s] < to[y])))
x = s;
pas--;
}
return t[0][x];
}
int main()
{
fin >> n >> m;
for (int i = 2; i <= n; i++)
{
int a;
fin >> a;
add(a, i);
}
dfs(1);
for (int i = 1; (1 << i) <= n; i++)
for (int j = 1; j <= n; j++)
t[i][j] = t[i - 1][t[i - 1][j]];
for (int i = 1; i <= m; i++)
{
int x, y;
fin >> x >> y;
fout << lca(x, y) << '\n';
}
fin.close();
fout.close();
return 0;
}