Pagini recente » Cod sursa (job #2842310) | Cod sursa (job #30975) | Cod sursa (job #238500) | Cod sursa (job #2733734) | Cod sursa (job #2672510)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int NMax = 100000;
int N,M;
vector <int> G[NMax + 5];
int Use[NMax + 5],TT[NMax + 5],Level[NMax + 5];
void Read()
{
fin >> N >> M;
for(int i = 2; i <= N; ++i)
{
fin >> TT[i];
G[TT[i]].push_back(i);
}
}
void DFS(int Nod)
{
Use[Nod] = 1;
for(int i = 0; i < (int)G[Nod].size(); ++i)
{
int Vecin = G[Nod][i];
if(!Use[Vecin])
{
Level[Vecin] = Level[Nod] + 1;
DFS(Vecin);
}
}
}
void SolveandPrint()
{
DFS(1);
while(M--)
{
int x,y;
fin >> x >> y;
if(Level[x]<Level[y])
swap(x,y);
while(Level[x] != Level[y])
x = TT[x];
while(x != y)
{
x = TT[x];
y = TT[y];
}
fout << x << "\n";
}
}
int main()
{
Read();
SolveandPrint();
return 0;
}