Pagini recente » Cod sursa (job #1488912) | Cod sursa (job #2420528) | Cod sursa (job #3148843) | Cod sursa (job #1070265) | Cod sursa (job #1568792)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int NMax = 100005;
int N,M;
vector<int> G[NMax];
int TT[NMax],Level[NMax];
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);
}
}
void SolveandPrint()
{
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();
DFS(1);
SolveandPrint();
return 0;
}