Pagini recente » Cod sursa (job #3345970) | Monitorul de evaluare | Cod sursa (job #3351886) | Cod sursa (job #3356531) | Cod sursa (job #3348100)
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
ifstream fin ("lca.in");
ofstream fout ("lca.out");
const int mxN = 1e5 + 1;
vector<int> G[mxN];
int n, m, rmq[mxN * 3][20], depth[mxN], indParc = 0, first[mxN];
void DFS(int nod){
rmq[++indParc][0] = nod;
for(int x : G[nod])
if(!first[x]){
depth[x] = depth[nod] + 1;
first[x] = indParc + 1;
DFS(x);
rmq[++indParc][0] = nod;
}
}
void initRmq(){
long long ind = 1, aux = 2;
for(int i = 1; i <= indParc; i++)
cout << rmq[i][0] << " ";
cout << "\n";
while(aux <= indParc){
for(int i = 1; i <= indParc - aux + 1; i++){
if(depth[rmq[i][ind - 1]] <= depth[rmq[i + aux / 2][ind - 1]])
rmq[i][ind] = rmq[i][ind - 1];
else
rmq[i][ind] = rmq[i + aux / 2][ind - 1];
cout << rmq[i][ind] << " ";
}
cout << "\n";
ind++;
aux *= 2;
}
}
int compute(int l, int r){
int ans = rmq[l][0], aux = 0;
while(r){
if(r % 2){
if(depth[ans] > depth[rmq[l][aux]])
ans = rmq[l][aux];
l += (1 << aux);
}
r /= 2;
aux++;
}
return ans;
}
int main(){
fin >> n >> m;
for(int i = 2; i <= n; i++){
int a;
fin >> a;
G[a].push_back(i);
}
depth[1] = 0;
first[1] = 1;
DFS(1);
initRmq();
for(int i = 1; i <= n; i++)
cout << first[i] << " ";
cout << "\n";
for(int i = 1; i <= m; i++){
int a, b;
fin >> a >> b;
if(first[a] > first[b])
swap(a, b);
fout << compute(first[a], first[b] - first[a] + 1) << "\n";
}
}