Pagini recente » Cod sursa (job #2766693) | Cod sursa (job #3292537) | Cod sursa (job #2464894) | Cod sursa (job #1713313) | Cod sursa (job #2605512)
#include <iostream>
#include <cstdio>
#include <vector>
#include <fstream>
using namespace std;
const int N = 100001;
const int L = 17;
ifstream fin("lca.in");
ofstream fout("lca.out");
int ti[N], to[N], tata[N];
int t[17][N];
/// t[i][j] = al 2^i lea tata al nodului j
/// ti[x] = timpul de intrare in nodul x
/// to[x] = timpul de iesire din nodul x
vector <int> g[N];
int timp;
void dfs(int node){
ti[node] = ++timp;
for(int p=0; p<(int)g[node].size(); p++){
int next = g[node][p];
dfs(next);
}
to[node] = ++ timp;
}
bool stramos(int x, int y){
return (ti[x] <= ti[y] && to[y] <= to[x]);
}
int lca(int x, int y){
if(stramos(x, y))
return x;
int pas = L - 1;
int s;
while(pas >= 0){
s = t[pas][x];
if(s != 0 && !stramos(s, y))
x = s;
pas--;
}
return t[0][x];
}
int main()
{
int n,m,i,j,x,y;
fin >> n >> m;
for(i=2; i<=n; i++){
fin >> tata[i];
g[tata[i]].push_back(i);
t[0][i] = tata[i];
}
dfs(1);
for(i=1; (1<<i) <= n; i++)
for(j=1; j <= n; j++)
t[i][j] = t[i-1][t[i-1][j]];
for(i=0; i<m; i++){
fin >> x >> y;
fout << lca(x, y) << "\n";
}
return 0;
}