Pagini recente » Cod sursa (job #374451) | Cod sursa (job #2141317) | Cod sursa (job #187862) | Cod sursa (job #1929856) | Cod sursa (job #1892395)
#include <fstream>
#include <vector>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
const int H = 201;
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 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() {
f >> n >> m;
for (i = 2; i <= n; i++) {
f >> tt[i];
ls[tt[i]].push_back(i);
}
df(1,0,0);
while (m--) {
f >> x >> y;
g << query(x,y) << '\n';
}
return 0;
}