Pagini recente » Cod sursa (job #2450066) | Cod sursa (job #544366) | Cod sursa (job #2470659) | Cod sursa (job #878168) | Cod sursa (job #2214774)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
int nivel[100010], tati[100010];
vector < vector<int>> v;
int DFS(int nod, int nivel_actual)
{
nivel[nod] = nivel_actual;
for(int i = 0; i < v[nod].size(); i++)
DFS(v[nod][i], nivel_actual + 1);
}
int query(int x, int y)
{
while(nivel[x] > nivel[y])
x = tati[x];
while(nivel[y] > nivel[x])
y = tati[y];
if(x == y)
return x;
while(x != y)
{
x = tati[x];
y = tati[y];
}
return x;
}
int main()
{
int n, m;
f >> n >> m;
v.resize(n + 2);
for(int i = 2 ; i <= n ; i++)
{
int x;
f >> x;
v[x].push_back(i);
tati[i] = x;
}
DFS(1, 0);
for(int i = 0 ; i < m; i++)
{
int x, y;
f >> x >> y;
g << query(x, y) << '\n';
}
}