Pagini recente » Cod sursa (job #262092) | Rezultatele filtrării | Cod sursa (job #540140) | Cod sursa (job #160744) | Cod sursa (job #1900184)
#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){
if(x == y)
return x;
if(D[x] == D[y] && ant[x] == ant[y])
return ant[x];
if(D[x] == D[y])
return LCA(ant[x],ant[y]);
if(D[x] < D[y])
return LCA(x,ant[y]);
else
return LCA(ant[x],y);
}
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;
}