Pagini recente » Cod sursa (job #1340393) | Cod sursa (job #2183234) | Cod sursa (job #871120) | Cod sursa (job #1076581) | Cod sursa (job #3238593)
#include <bits/stdc++.h>
using namespace std;
ifstream f ("lca.in");
ofstream g ("lca.out");
const int NMAX = 1e5;
const int L = 21;
int dp[NMAX+1][L+1];
int t_in[NMAX+1], t_out[NMAX+1]; // timpii de iesire, respectiv intrare in dfs
bool marked[NMAX+1];
int n, q, timp;
vector<int> adj[NMAX+1];
void calcul_stramosi(){
for(int j=1; (1 << j) <= n; j++)
for(int i=1; i<=n; i++)
dp[i][j] = dp[dp[i][j-1]][j-1];
}
void dfs(int nod){
t_in[nod] = ++timp;
marked[nod] = true;
for(int next : adj[nod])
if(!marked[next])
dfs(next);
t_out[nod] = ++timp;
}
bool e_stramos(int x, int y){
if(t_in[x] <= t_in[y] and t_out[x] >= t_out[y])
return true;
return false;
}
int lca(int x, int y){
if(e_stramos(x, y))
return x;
int pas = L;
while(pas >= 0){
if(dp[x][pas] != 0 and !e_stramos(dp[x][pas], y))
x = dp[x][pas];
pas --;
}
return dp[x][0];
}
int main()
{
f >> n >> q;
for(int i=2; i<=n; i++){
f >> dp[i][0];
adj[dp[i][0]].push_back(i); // i este fiul lui dp[i][0] (tatal lui i)
}
calcul_stramosi();
dfs(1);
for(int i=1; i<=q; i++){
int x, y;
f >> x >> y;
g << lca(x, y) << "\n";
}
return 0;
}