Pagini recente » Cod sursa (job #1852510) | Cod sursa (job #1984510) | Cod sursa (job #2203773) | Cod sursa (job #3172061) | Cod sursa (job #2046488)
#include <bits/stdc++.h>
using namespace std;
struct thing{
int x, d;
};
int n, test, p, depth[100005], tt[100005], euclid[200005], first_pos[100005], lg2[200005];
thing pd[20][100005];
vector<int> v[100005];
thing min(thing a, thing b)
{
if(a.d < b.d)
return a;
return b;
}
thing make_thing(int x, int d)
{
thing aux;
aux.x = x;
aux.d = d;
return aux;
}
void dfs (int x)
{
depth[x] = depth[tt[x]]+1;
++p;
euclid[p] = x;
first_pos[x] = p;
for (vector<int>::iterator it = v[x].begin(); it != v[x].end(); ++it){
dfs(*it);
euclid[++p] = x;
}
}
void build_rmq()
{
for (int i = 1; i < p; ++i){
pd[0][i] = make_thing(euclid[i], depth[euclid[i]]);
if(depth[euclid[i]] > depth[euclid[i+1]])
pd[0][i] = make_thing(euclid[i+1], depth[euclid[i+1]]);
}
for (int t = 1; t <= lg2[p-1]; ++t)
for (int i = 1; i <= p-(1<<t); ++i)
pd[t][i] = min(pd[t-1][i], pd[t-1][i+(1<<(t-1))]);
}
int query(int x, int y)
{
if (x == y)
return x;
if(first_pos[x] > first_pos[y])
swap(x, y);
int sz = lg2[first_pos[y]-first_pos[x]];
thing aux = min(pd[sz][first_pos[x]], pd[sz][first_pos[y]-(1<<sz)]);
return aux.x;
}
int main()
{
ifstream fin ("lca.in");
ofstream fout ("lca.out");
fin >> n >> test;
for (int i = 2; i <= n; ++i){
int x;
fin >> x;
v[x].push_back(i);
tt[i] = x;
}
dfs(1);
lg2[2] = 1;
for (int i = 3; i < 200005; ++i)
lg2[i] = lg2[i/2]+1;
build_rmq();
while(test--){
int x, y;
fin >> x >> y;
fout << query(x, y) << "\n";
}
fin.close();
fout.close();
return 0;
}