Pagini recente » Cod sursa (job #1807966) | Cod sursa (job #2258340) | Cod sursa (job #355599) | Arhiva de probleme | Cod sursa (job #2674656)
#include <bits/stdc++.h>
#define MAX 100005
#define NMAX 400100
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
struct ex{
int e, nivel;
}v[MAX];
int n, m, t[MAX], r, z, poz, val, x, y, minim, pozminim;
map < int , int > hashis;
bitset < MAX > c;
stack < int > st;
void Euler(int k){
st.push(k);
v[++z].e = k;
v[z].nivel = st.size() - 1;
if(!hashis[k])
hashis[k] = z;
c[k] = true;
for(int i = 1; i <= n; i++)
if(!c[i] && t[i] == k)
Euler(i);
st.pop();
if(t[k]){
v[++z].e = t[k];
v[z].nivel = st.size() - 1;
}
}
int main(){
in>>n>>m;
for(int i = 2; i <= n; i++)
in>>t[i];
Euler(1);
for(int i = 1; i <= z; i++){
poz = i, val = v[i].nivel;
}
Euler(1);
while(m){
in>>x>>y;
x = hashis[x], y = hashis[y];
if(x > y)
x ^= y, y ^= x, x ^= y;
minim = (1 << 30), pozminim = 0;
for(int i = x; i <= y; i++){
if(minim > v[i].nivel)
minim = v[i].nivel, pozminim = i;
}
out<<v[pozminim].e<<"\n";
m--;
}
}