Pagini recente » Cod sursa (job #3254950) | Cod sursa (job #2490737) | Cod sursa (job #1480899) | Cod sursa (job #813130) | Cod sursa (job #2977215)
#include <bits/stdc++.h>
//#pragma GCC optimize("unroll-loops")
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
/*int Time(){
return chrono::steady_clock::now().time_since_epoch().count();
}
random_device rd;
mt19937_64 gen(rd());
int uniform_rand(int l, int r){
uniform_int_distribution<ll> rnd(l,r);
return rnd(gen);
}*/
const int NMAX=2.5e5+5,LGMAX=18;
ifstream fin("lca.in");
ofstream fout("lca.out");
vector<ll> edg[NMAX];
ll ln[NMAX],rn[NMAX];
int p[LGMAX][NMAX],eid;
void gheal_tour(ll u){
ln[u]=1e6;
for(auto it : edg[u]){
if(it!=p[0][u]){
gheal_tour(it);
ln[u]=min(ln[u],ln[it]);
}
}
rn[u]=++eid;
if(ln[u]==1e6) ln[u]=rn[u];
}
bool is_ancestor(ll u, ll v){
return u==0 || (ln[u]<=ln[v] && rn[v]<=rn[u]);
}
ll LCA(ll u, ll v){
if(is_ancestor(u,v)) return u;
for(ll bit=LGMAX-1;bit>=0;bit--)
if(!is_ancestor(p[bit][u],v))
u=p[bit][u];
return p[0][u];
}
int main()
{
ios_base::sync_with_stdio(false);
ll n,q;
fin>>n>>q;
for(ll i=2;i<=n;i++){
fin>>p[0][i];
edg[p[0][i]].push_back(i);
}
gheal_tour(1);
for(ll bit=1;bit<LGMAX;bit++)
for(ll i=1;i<=n;i++)
p[bit][i]=p[bit-1][p[bit-1][i]];
while(q--){
ll x,y;
fin>>x>>y;
fout<<LCA(x,y)<<'\n';
}
return 0;
}