Pagini recente » Cod sursa (job #433575) | Cod sursa (job #334568) | Cod sursa (job #2482829) | Cod sursa (job #1150930) | Cod sursa (job #1900195)
#include <bits/stdc++.h>
#define NMAX 100005
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int D[NMAX],ant[NMAX];
vector < int > G[NMAX];
void DFS(const int &nod){
for(auto const &it : G[nod]){
D[it] = D[nod] + 1;
DFS(it);
}
}
int LCA(int x,int y){
while(x != y){
if(D[x] > D[y])
x = ant[x];
else
y = ant[y];
}
return x;
}
int main()
{
ios :: sync_with_stdio(false);
int n,m,x,y;
fin >> n >> m;
for(int i = 2; i <= n; i++){
fin >> ant[i];
G[ant[i]].push_back(i);
}
DFS(1);
for(int i = 1; i <= m; i++){
fin >> x >> y;
fout << LCA(x,y) << "\n";
}
return 0;
}