Pagini recente » Cod sursa (job #315921) | Cod sursa (job #865887) | Cod sursa (job #693373) | Cod sursa (job #438808) | Cod sursa (job #1892399)
#include <fstream>
#include <list>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
const int H = 400;
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() {
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;
}