Pagini recente » Cod sursa (job #1430833) | Cod sursa (job #2649512) | Cod sursa (job #57009) | Cod sursa (job #2426595) | Cod sursa (job #1533626)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
#define MAX 100010
typedef vector <int> :: iterator iter;
vector <int> G[MAX];
int depth[MAX], dr, dad[MAX], st[20][2 * MAX], poz[MAX], lg[2 * MAX];
void df(int nod)
{
depth[nod] = depth[dad[nod]] + 1;
st[0][++dr] = nod;
poz[nod] = dr;
for(iter it = G[nod].begin() ; it != G[nod].end() ; it++)
{
df(*it);
st[0][++dr] = nod;
}
}
int main()
{
int q, i, n, j, x, y;
fin >> n >> q;
lg[0] = -1;
for(i = 2 ; i <= n ; i++)
{
fin >> dad[i];
G[dad[i]].push_back(i);
}
df(1);
for(i = 1 ; i <= dr ; i ++)
{
lg[i] = lg[i / 2] + 1;
// cout << st[0][i] << " ";
}
// cout << "\n";
for(j = 1 ; (1 << j) <= dr ; j++)
{
for(i = 1 ; i + (1 << j) - 1 <= dr ; i++)
{
if(depth[st[j - 1][i]] < depth[st[j - 1][i + (1<<(j - 1))]])
st[j][i] = st[j - 1][i];
else
st[j][i] = st[j - 1][i + (1 << (j - 1))];
}
}
while(q--)
{
fin >> x >> y;
x = poz[x];
y = poz[y];
if(y < x)
swap(x, y);
int dist = y - x + 1;
dist = lg[dist];
if(depth[st[dist][x]] < depth[st[dist][y - (1 << dist) + 1]])
fout << st[dist][x] << "\n";
else
fout << st[dist][y - (1 << dist) + 1] << "\n";
}
}