Pagini recente » Cod sursa (job #637593) | Cod sursa (job #1152169) | Cod sursa (job #2399852) | Cod sursa (job #1598874) | Cod sursa (job #1280072)
#include<fstream>
#include<vector>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
const int nmax = 100006;
int n, m, d[18][nmax], nivel[nmax];
vector<int> fii[nmax];
int lca(int x, int y)
{
if(nivel[x]<nivel[y])
{
int p = nivel[y] - nivel[x];
for(int i = 0; p!=0; p/=2, i++)
if(p%2==1)
y = d[i][y];
}
else
{
int p = nivel[x] - nivel[y];
for(int i = 0; p!=0; p/=2, i++)
if(p%2==1)
x = d[i][x];
}
for(int i = 14; i>=0; i--)
{
if(d[i][x]!=d[i][y])
{
x = d[i][x];
y = d[i][y];
}
}
if(x==y)
return x;
else
return d[0][x];
}
void dfs(int x, int level)
{
nivel[x] = level;
for(int i = 0; i<(int)fii[x].size(); i++)
dfs(fii[x][i], level + 1);
}
int main(){
int player_unu=0;
in>>n>>m;
for(int i = 2; i<=n; i++)
{
in>>d[0][i];
fii[d[0][i]].push_back(i);
}
dfs(1, 1);
for(int i = 1; i<=17; i++)
for(int j = 1; j<=n; j++)
d[i][j] = d[i - 1][d[i - 1][j]];
for(int i = 0; i<m; i++)
{
int x, y;
in>>x>>y;
out<<lca(x, y)<<'\n';
}
return player_unu;
}