Pagini recente » Cod sursa (job #163542) | Cod sursa (job #1516720) | Cod sursa (job #177644) | Cod sursa (job #40913) | Cod sursa (job #2859066)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int n, m;
vector<int>V[100005];
int lol[100005];
int stra[100005][18];
int nivel[100005];
void DFS(int nod)
{
for(auto x : V[nod])
{
nivel[x] = nivel[nod] + 1;
DFS(x);
}
}
void Query(int x, int y)
{
int i;
if(nivel[x] > nivel[y])
swap(x, y);
for(i = 17;i >= 0;i--)
if(nivel[stra[y][i]] >= nivel[x])
y = stra[y][i];
cout << x << " " << y << "\n";
if(x != y)
{
for(i = 17;i >= 0;i--)
if(stra[y][i] != stra[x][i])
{
y = stra[y][i];
x = stra[x][i];
}
fout << stra[x][0] << "\n";
}
else
fout << x << "\n";
}
void Citire()
{
int i, x, j, y;
fin >> n >> m;
for(i = 2;i <= n;i++)
{
fin >> x;
stra[i][0] = x;
V[x].push_back(i);
}
lol[1] = 0;
for(i = 2;i <= n;i++)
lol[i] = lol[i / 2] + 1;
int N = lol[n];
for(i = 2;i <= n;i++)
for(j = 1;j <= N;j++)
stra[i][j] = stra[stra[i][j - 1]][j - 1];
nivel[1] = 1;
DFS(1);
for(i = 1;i <= m;i++)
{
fin >> x >> y;
Query(x, y);
}
}
int main()
{
Citire();
return 0;
}