Pagini recente » Cod sursa (job #502177) | Cod sursa (job #2665094) | Cod sursa (job #1247935) | Cod sursa (job #599966) | Cod sursa (job #1892413)
#include <cstdio>
#include <vector>
using namespace std;
int H = 220;
int n,i,x,y,m;
int nv[100005];
int tt[100005];
int ttm[100005];
vector<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;
for (i = 0; i<l; i++) {
y = ls[x][i];
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 y=ttm[y];
}
while (x != y) {
if (nv[x]>nv[y])
x = tt[x];
else 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,1,0);
while (m--) {
scanf("%d %d\n",&x,&y);
printf("%d\n",query(x,y));
}
return 0;
}