Pagini recente » Cod sursa (job #2705616) | Cod sursa (job #1786451) | Cod sursa (job #3032823) | Cod sursa (job #2321621) | Cod sursa (job #1971162)
#include <fstream>
#include <vector>
using namespace std;
#define MAX_N 100005
ifstream fin ("lca.in");
ofstream fout ("lca.out");
const int h = 200;
int N, M, T[MAX_N], T2[MAX_N], Lev[MAX_N];
vector <int> G[MAX_N];
void citire()
{
fin >> N >> M;
for(int i = 2; i <= N; ++i)
{
fin >> T[i];
G[T[i]].push_back(i);
}
}
void dfs(int nod, int n1, int lev)
{
Lev[nod] = lev;
T2[nod] = n1;
if(lev % h == 0) n1 = nod;
for(int i =0;i<G[nod].size();i++)
dfs(G[nod][i], n1, lev+1);
}
int lca(int x, int y)
{
while(T2[x] != T2[y])
if(Lev[x] > Lev[y])
x = T2[x];
else
y = T2[y];
while(x != y)
if(Lev[x] > Lev[y])
x = T[x];
else
y = T[y];
return x;
}
int main()
{
citire();
dfs(1, 0, 0);
while(M--)
{
int x, y;
fin >> x >> y;
fout << lca(x, y) << "\n";
}
}