Pagini recente » Cod sursa (job #1401758) | Cod sursa (job #847296) | Cod sursa (job #1543179) | Cod sursa (job #2364026) | Cod sursa (job #2910061)
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
int n,m;
int LOG;
int up[250005][19],depth[100005];
vector<int> children[100005];
int x,y;
void Citire()
{
f>>n>>m;
}
void dfs(int a)
{
for(int i : children[a])
{
depth[i] = depth[a]+1;
up[i][1] = a;
for(int j=2;j<=LOG;j++)
{
up[i][j] = up[up[i][j-1]][j-1];
}
dfs(i);
}
}
int LCA(int a, int b)
{
if(depth[a]<depth[b])
swap(a,b);
int k = depth[a] - depth[b];
for(int i=LOG;i>=1;i--)
{
if(k&(1<<(i-1)))
a = up[a][i];
}
if(a==b)
return a;
for(int i = LOG; i>=1;i--)
{
if(up[a][i] != up[b][i])
{
a=up[a][i];
b=up[b][i];
}
}
return up[a][1];
}
int main()
{
Citire();
while(1<<LOG<=n)
LOG++;
for(int i=2;i<=n;i++)
{
int x;
f>>x;
children[x].push_back(i);
}
dfs(1);
for(int i=1;i<=m;i++)
{
f>>x>>y;
g<<LCA(x,y)<<"\n";
}
}