Pagini recente » Cod sursa (job #2305306) | Cod sursa (job #3032675) | Cod sursa (job #2762049) | Cod sursa (job #2162251) | Cod sursa (job #2441455)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int n;
int anc[MAXN];
int solve1(int x, int y){
int strx = anc[x], stry = anc[y];
while(strx != stry){
if(strx > stry) strx = anc[strx];
else if(strx < stry) stry = anc[stry];
}
return strx;
}
int main()
{
ifstream fin("lca.in");
ofstream fout("lca.out");
int m;
fin >> n >> m;
anc[1] = 1;
for(int i = 2; i <= n; ++i)
fin >> anc[i];
while(m){
int x, y;
fin >> x >> y;
if(x == anc[y] || y == anc[x] || x == y){
if(x == anc[y]) fout << x << "\n";
else fout << y << "\n";
m--;
continue;
}
fout << solve1(x, y) << "\n";
m--;
}
return 0;
}