Pagini recente » Cod sursa (job #1131134) | Istoria paginii runda/piscot1024 | Cod sursa (job #858313) | Cod sursa (job #1005859) | Cod sursa (job #1892406)
#include <cstdio>
#include <list>
using namespace std;
int H = 800;
int n,i,x,y,m;
int nv[100005];
int tt[100005];
int ttm[100005];
list<int>ls[100005];
void df(int x, int tm, int niv) {
ttm[x] = tm;
if (niv%H == 0)
tm = x;
nv[x] = niv;
int i, l = ls[x].size(), y;
list<int>::iterator w;
for (w = ls[x].begin(); w!=ls[x].end(); w++) {
y = *w;
if (nv[y] == 0)
df(y,x,niv+1);
}
}
int query(int x, int y) {
while (ttm[x]!=ttm[y]) {
if (nv[x]>nv[y])
x = ttm[x];
else if (nv[x]<nv[y])
y = ttm[y];
else x=ttm[x],y=ttm[y];
}
while (x != y) {
if (nv[x]>nv[y])
x = tt[x];
else if (nv[x]<nv[y])
y = tt[y];
else x=tt[x],y=tt[y];
}
return x;
}
int main() {
freopen("lca.in","r",stdin);
freopen("lca.out","w",stdout);
scanf("%d %d\n", &n,&m);
for (i = 2; i <= n; i++) {
scanf("%d ", &tt[i]);
ls[tt[i]].push_back(i);
}
df(1,0,0);
while (m--) {
scanf("%d %d\n",&x,&y);
printf("%d\n",query(x,y));
}
return 0;
}