Pagini recente » Cod sursa (job #957978) | Cod sursa (job #1882523) | Cod sursa (job #2906367) | Cod sursa (job #1664450) | Cod sursa (job #3003890)
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
const int nmax = 1e5;
vector<int>g[nmax + 1];
int nivel[nmax + 1];
int n;
int stramosi[18][nmax + 1];
void dfs(int node,int lvl)
{
nivel[node] = lvl;
lvl++;
for(int i = 0; i < g[node].size(); i++)
{
int vecin = g[node][i];
if(nivel[vecin] == 0)
dfs(vecin,lvl);
}
}
void build_stramosi()
{
int l2 = log2(n);
for(int i = 1; i <= l2; i++)
for(int j = 1; j <= n; j++)
stramosi[i][j] = stramosi[i - 1][stramosi[i - 1][j]];
}
int equalize(int node, int down)
{
int l2 = log2(n);
for(int i = l2; i >= 0; i--)
if(stramosi[i][node] != 0 && (1<<i) <= down && nivel[node] - 1 >= (1<<i))
{
node = stramosi[i][node];
down -= (1<<i);
}
return node;
}
void findstramos(int x,int y)
{
if(x == y)
out<<x<<'\n';
else
{
int l2 = log2(n);
for(int i = l2; i >= 0; i--)
{
if(stramosi[i][x] != stramosi[i][y])
{
x = stramosi[i][x];
y = stramosi[i][y];
}
}
out<<stramosi[0][x]<<'\n';
}
}
int main()
{
int m;
in>>n>>m;
for(int i = 2; i <= n; i++)
{
in>>stramosi[0][i];
g[stramosi[0][i]].push_back(i);
}
dfs(1,1);
build_stramosi();
for(int i = 1; i <= m; i++)
{
int x,y;
in>>x>>y;
if(nivel[x] != nivel[y])
{
if(nivel[x] < nivel[y])
{
int down = nivel[y] - nivel[x];
int copil = equalize(y, down);
findstramos(copil,x);
}
else if(nivel[x] > nivel[y])
{
int down = nivel[x] - nivel[y];
int copil = equalize(x,down);
findstramos(copil,y);
}
}
else
findstramos(x,y);
}
return 0;
}