Pagini recente » Cod sursa (job #52866) | Cod sursa (job #2950474) | Cod sursa (job #1935976) | Cod sursa (job #282031) | Cod sursa (job #2764678)
#include <bits/stdc++.h>
#define LOG 17
#define NMAX 100005
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
int n, Q, depth[NMAX], up[NMAX][LOG + 1];
bitset <NMAX> v;
vector <int> Muchii[NMAX];
void dfs(int nod)
{
v[nod] = 1;
for(auto child : Muchii[nod])
if(!v[child])
{
depth[child] = depth[nod] + 1;
up[child][0] = nod;
for(int i = 1; i <= LOG; i++)
up[child][i] = up[up[child][i - 1]][i - 1];
dfs(child);
}
}
int lca(int a, int b)
{
if(depth[a] < depth[b])
swap(a, b);
int k = depth[a] - depth[b];
for(int i = LOG; i >= 0; i--)
if(k & (1 << i))
a = up[a][i];
if(a == b)
return a;
for(int i = LOG; i >= 0; i--)
if(up[a][i] != up[b][i])
{
a = up[a][i];
b = up[b][i];
}
return up[a][0];
}
int main()
{
f >> n >> Q;
for(int i = 2; i <= n; i++)
{
int x;
f >> x;
Muchii[x].push_back(i);
}
dfs(1);
for(int i = 1, x, y; i <= Q; i++)
{
f >> x >> y;
g << lca(x, y) << "\n";
}
return 0;
}