Pagini recente » Cod sursa (job #1836444) | Cod sursa (job #547553) | Cod sursa (job #1737682) | Cod sursa (job #1860431) | Cod sursa (job #2095169)
#include <bits/stdc++.h>
using namespace std;
struct thing{
int x, d;
bool operator<(const thing &obj)const{
return d < obj.d;
}
}pd[20][400005];
int n, t, a, b, nodes[200005], euclid[400005], p, first[200005], depth[200005], lg2[400005], up[20][200005], tt[200005];
vector<int> v[200005];
thing make_thing (int x, int d)
{
thing aux;
aux.x = x;
aux.d = d;
return aux;
}
void build_rmq()
{
for (int i = p; i > 0; --i){
pd[0][i] = make_thing(euclid[i], depth[euclid[i]]);
for (int d = 1; i+(1<<d) <= p; ++d)
pd[d][i] = min(pd[d-1][i], pd[d-1][i+(1<<(d-1))]);
}
}
int rmq_query(int x, int y)
{
if(x == y)
return x;
if(first[x] > first[y])
swap(x, y);
int lg = lg2[first[y]-first[x]];
return min(pd[lg][first[x]], pd[lg][first[y]-(1<<lg)]).x;
}
void df(int x, int pred = 0)
{
depth[x] = depth[pred] + 1;
tt[x] = pred;
//up[0][]
euclid[++p] = x;
first[x] = p;
vector<int>::iterator er;
for (vector<int>::iterator it = v[x].begin(); it != v[x].end(); ++it)
if(*it == pred)
er = it;
else{
df(*it, x);
euclid[++p] = x;
}
if(x != 1)
v[x].erase(er);
}
int dist(int u1, int u2)
{
}
int main()
{
ifstream fin ("lca.in");
ofstream fout ("lca.out");
fin >> n >> t;
for (int i = 2; i <= n; ++i){
/*int x, y;
fin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);*/
int x;
fin >> x;
v[x].push_back(i);
v[i].push_back(x);
}
df(1);
lg2[2] = 1;
for (int i = 3; i < 400005; ++i)
lg2[i] = lg2[i/2]+1;
build_rmq();
fin >> a >> b;
nodes[1] = a;
nodes[2] = b;
fout << rmq_query(a, b) << "\n";
for (int i = 2; i <= t; ++i){
/*int u;
fin >> u;
nodes[i] = u;*/
int x, y;
fin >> x >> y;
fout << rmq_query(x, y) << "\n";
}
fin.close();
fout.close();
return 0;
}