Pagini recente » Cod sursa (job #1733211) | Cod sursa (job #1112487) | Cod sursa (job #3243568) | Cod sursa (job #2799861) | Cod sursa (job #1217828)
#include <iostream>
#include <fstream>
#include <map>
#include <string.h>
#include <string>
#include <vector>
#include <set>
#include <math.h>
#include <algorithm>
#include <iomanip>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int n,m;
int dp[100000][19];
int l[100000];
int geta(int a, int x)
{
int t = a;
int i=0;
while (x)
{
if (x & (1<<i))
{
x = x^(1<<i);
t = dp[t][i];
}
i++;
}
return t;
}
int process(int x, int y)
{
if ( l[x]>l[y] )
{
int d = l[x]-l[y];
x = geta(x,d);
}
else if (l[x] < l[y])
{
int d = l[y]-l[x];
y = geta(y,d);
}
if (x==y) return x;
int ll = 0,rr = log2(l[x])+1;
while (ll<rr)
{
int mm = (ll+rr)/2 + (ll+rr)%2;
if (dp[x][mm] != dp[y][mm])
ll=mm;
else rr=mm-1;
}
x = dp[x][ll];
y = dp[y][ll];
return process(x,y);
}
int main()
{
fin>>n>>m;
dp[0][0] = 0;
l[0]=0;
for (int i=1; i<n; i++)
{
fin>>dp[i][0];
dp[i][0]--;
l[i] = l [ dp[i][0] ]+1;
for (int j=1; (1<<(j-1)) <= l[i] ; j++)
dp[i][j] = dp[dp[i][j-1]][j-1];
}
for (int i=0; i<m; i++)
{
int x,y;
fin>>x>>y;
x--;
y--;
fout<<process(x,y)+1<<'\n';
}
return 0;
}