Cod sursa(job #1350026)

Utilizator mikeshadowIon Complot mikeshadow Data 20 februarie 2015 16:58:53
Problema Lowest Common Ancestor Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <math.h>

using namespace std;

ifstream fin("lca.in");
ofstream fout ("lca.out");

int n;
int dp[100000][17];
int dep[100000];

void init()
{
	for (int i = 1; 1 << i < n; i++)
		for (int j = 0; j < n; j++)
			dp[j][i] = dp[ dp[j][i - 1] ][i - 1];
}

int getp(int x, int d)
{
	int c = x;
	while (d)
	{
		int k = 0;
		k = log2(d);
		d ^= 1 << k;
		c = dp[c][k];
	}
	return c;
}

int lca(int x, int y)
{
	if (dep[x] < dep[y])
		y = getp(y, dep[y] - dep[x]);
	else x = getp(x, dep[x] - dep[y]);


	for (int i = log2(dep[x]); i >= 0 && x != y; i--)
		if (dp[x][i] != dp[y][i])
		{
			x = dp[x][i];
			y = dp[y][i];
			i = min(i, (int)log2(dep[x]));
		}
	if (x!=y) x = dp[x][0];
	return x;
}

int m;


int main()
{
	fin >> n>>m;
	dep[0] = 0;
	dp[0][0] = 0;
	for (int i = 1; i < n; i++)
	{
		fin >> dp[i][0];
		dp[i][0]--;
		if (i) dep[i] = dep[ dp[i][0] ] + 1;
	}
	init();

	for (int i=0; i<m; i++)
	{
		int x,y;
		fin>>x>>y;
		x--,y--;
		fout<<lca(x,y)+1<<'\n';
	}

	return 0;
}