Pagini recente » Cod sursa (job #1731869) | Cod sursa (job #1714998) | Cod sursa (job #2452289) | Clasament simulare-cartita-03 | Cod sursa (job #2565239)
#include <bits/stdc++.h>
#define nmax 100005
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int first_app[nmax], rmq[nmax][30], numere[3 * nmax], lungime_euler, n, m, start[nmax], ordine[nmax], ord;
vector <int> graph[nmax];
bool vizat[nmax];
void citire()
{
int x, i;
for(i = 2; i <= n; i++)
fin >> x, graph[x].push_back(i);
}
void dfs(int nod)
{
vizat[nod] = 1;
ordine[nod] = ord, start[ord] = nod, ord++;
numere[lungime_euler] = ordine[nod];
first_app[nod] = lungime_euler;
lungime_euler++;
unsigned i, len;
len = graph[nod].size();
for(i = 0; i < len; i++)
{
if(!vizat[graph[nod][i]])
{
dfs(graph[nod][i]);
numere[lungime_euler] = ordine[nod], lungime_euler++;
}
}
}
void sparse(int logeuler)
{
int i, j, z, t;
for(i = 0; i < lungime_euler; i++)
rmq[i][0] = numere[i];
for(j = 1; j <= logeuler; j++)
{
t = (1 << j);
z = (1 << (j - 1));
for(i = 0; i + t <= lungime_euler; i++)
{
if(start[rmq[i][j - 1]] < start[rmq[i + z][j - 1]])
rmq[i][j] = rmq[i][j - 1];
else
rmq[i][j] = rmq[i + z][j-1];
}
}
}
int get_lg(int a)
{
int x = 0;
while(a > 1)
{
a = (a >> 1);
x++;
}
return x;
}
int functie(int a, int b)
{
int k;
k = get_lg(b - a);
if(start[rmq[a][k]] < start[rmq[b - (1 << k) +1][k]])
return start[rmq[a][k]];
else
return start[rmq[b - (1 << k) + 1][k]];
}
int main()
{
int i, x, y;
fin >> n >> m;
citire();
dfs(1);
sparse(get_lg(lungime_euler));
for(i = 0; i < m; i++)
{
fin >> x >> y;
if(first_app[x] < first_app[y])
fout << functie(first_app[x], first_app[y]) << '\n';
else
fout << functie(first_app[y], first_app[x]) << '\n';
}
return 0;
}