Pagini recente » Cod sursa (job #833087) | Cod sursa (job #1393045) | Cod sursa (job #2339993) | Cod sursa (job #2809689) | Cod sursa (job #3307285)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int MAX=1e5;
int n,i,t[MAX+5],depth[MAX+5],node1,node2,q;
bool viz[MAX+5];
vector <int> edge[MAX+5];
void dfs(int node)
{
viz[node]=1;
for (auto node2: edge[node])
{
if (!viz[node2])
{
depth[node2]=depth[node]+1;
dfs(node2);
}
}
}
int lca(int x, int y)
{
if (depth[x]<depth[y])
swap(x,y);
while (depth[x]>depth[y])
x=t[x];
while (x!=y)
{
x=t[x];
y=t[y];
}
return x;
}
int main()
{
ios_base::sync_with_stdio(false);
fin.tie(0); fout.tie(0);
fin>>n>>q;
for (i=2; i<=n; i++)
{
fin>>t[i];
edge[i].push_back(t[i]);
edge[t[i]].push_back(i);
}
dfs(1);
while (q--)
{
fin>>node1>>node2;
fout<<lca(node1,node2)<<'\n';
}
return 0;
}