Pagini recente » Cod sursa (job #2734550) | Cod sursa (job #1307090) | Cod sursa (job #2990560) | Cod sursa (job #1376631) | Cod sursa (job #2976924)
#include <bits/stdc++.h>
#define Nmax 100005
#define LG 17
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int tin[Nmax], tout[Nmax], t[Nmax][LG], n, m, o;
vector <int> v[Nmax];
void dfs(int x)
{
tin[x] = ++o;
for(auto it:v[x])
if(it != t[x][0])
dfs(it);
tout[x] = ++o;
}
void binary_lift()
{
for(int j=1;j<LG;j++)
for(int i=1;i<=n;i++)
t[i][j] = t[t[i][j-1]][j-1];
}
bool is_ancestor(int x, int y)
{
if(tin[x] <= tin[y] && tout[y] <= tout[x])
return 1;
else return 0;
}
int lca(int x, int y)
{
if(is_ancestor(x, y))
return x;
if(is_ancestor(y, x))
return y;
for(int j=LG-1;j>=0;j--)
if(!is_ancestor(t[x][j], y))
x = t[x][j];
return t[x][0];
}
int main()
{
fin >> n >> m;
for(int i=2;i<=n;i++)
{
fin >> t[i][0];
v[t[i][0]].push_back(i);
}
t[1][0]=1;
dfs(1); ///radacina
binary_lift();
while(m--)
{
int x, y;
fin >> x >> y;
fout << lca(x, y) << '\n';
}
return 0;
}