Pagini recente » Cod sursa (job #2891637) | Cod sursa (job #1599181) | Cod sursa (job #4242) | Cod sursa (job #222254) | Cod sursa (job #2280305)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int NMax = 100000;
vector <int> G[NMax + 5];
int TT[NMax + 5], Level[NMax + 5];
int N,M;
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)
{
for(int i = 0; i < (int)G[Nod].size();++i)
{
int Vecin = G[Nod][i];
Level[Vecin] = Level[Nod] + 1;
DFS(Vecin);
}
}
int LCA(int x, int 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];
}
return x;
}
void SolveAndPrint()
{
while(M--)
{
int x,y;
fin >> x >> y;
fout << LCA(x,y) << "\n";
}
}
int main()
{
Read();
DFS(1);
SolveAndPrint();
return 0;
}