Pagini recente » Cod sursa (job #280285) | Cod sursa (job #2323636) | Cod sursa (job #773647) | Cod sursa (job #1764135) | Cod sursa (job #3233053)
#include <bits/stdc++.h>
using namespace std;
int nivel[100005], t[100005][25], i, n, nod, rasp, q, x, y;
vector<int>v[100005];
ifstream fin("lca.in");
ofstream fout("lca.out");
void dfs(int nod, int prec) {
nivel[nod]=nivel[prec]+1;
for (int i:v[nod]) {
if (i!=prec) dfs(i, nod);
}
}
int urca(int nod, int nr) {
for (i=0; i<=20; i++) {
if (nr%2==1) {
nod=t[nod][i];
}
nr/=2;
if (nr==0) break;
}
return nod;
}
int main()
{
fin>>n>>q;
for (i=2; i<=n; i++) {
fin>>t[i][0];
v[i].push_back(t[i][0]);
v[t[i][0]].push_back(i);
}
for (i=1; i<=20; i++) {
for (nod=1; nod<=n; nod++)
t[nod][i]=t[t[nod][i-1]][i-1];
}
dfs(1, 0);
while (q--) {
fin>>x>>y;
if (nivel[x]>nivel[y]) swap(x, y);
y=urca(y, nivel[y]-nivel[x]);
i=20;
if (x==y) {
rasp=x;
i=-1;
}
for (; i>=0; i--) {
int xx=t[x][i];
int yy=t[y][i];
if (xx==yy) {
rasp=xx;
}
else {
x=xx;
y=yy;
}
}
fout<<rasp<<'\n';
}
return 0;
}