Pagini recente » Cod sursa (job #3353217) | Cod sursa (job #3318950) | Cod sursa (job #3233344) | Monitorul de evaluare | Cod sursa (job #3346087)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int up[100001][20], depth[100001];
const int LOG=20; //ajunge pt 1e6
vector<int> graf[100001];
int n, q, x, y;
void dfs(int nod, int parinte)
{
up[nod][0]=parinte;
for (int j=1; j< LOG; j++)
{
up[nod][j]=up[ up[nod][j-1] ][j-1];
}
for (auto u: graf[nod])
{
if (u==parinte) continue;
depth[u]=depth[nod]+1;
dfs(u, nod);
}
}
int lift(int a, int k)
{
for (int j=0; j<LOG; j++)
{
if (k&(1<<j))
{
a=up[a][j];
}
}
return a;
}
int lcaquery(int a, int b)
{
if (depth[a]<depth[b])
{
swap(a, b);
}
//acumaducem pe a la aceeasi adancime cu b
a=lift(a, depth[a]-depth[b]);
if (a==b)
{
return a;
}
for (int j=LOG-1; j>=0; j--)
{
if (up[a][j]!=up[b][j])
{
a=up[a][j];
b=up[b][j];
}
}
return up[a][0];
}
int main()
{
fin>>n>>q;
for (int i=2; i<=n; i++)
{
fin>>x;
graf[x].push_back(i);
graf[i].push_back(x);
}
depth[1]=1;
dfs(1, 0);
for (int i=1; i<=q; i++)
{
fin>>x>>y;
fout<<lcaquery(x, y)<<'\n';
}
return 0;
}