Cod sursa(job #935618)

Utilizator DaNutZ2UuUUBB Bora Dan DaNutZ2UuU Data 4 aprilie 2013 12:27:07
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include<fstream>
#include<algorithm>
#include<vector>
#define nmax 100005

using namespace std;

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

int h = 200;
int m, n, a[nmax], tata[nmax], niv[nmax];
vector <int> v[nmax];

void Dfs(int nod, int n1, int lev)
{
	niv[nod] = lev;
	tata[nod] = n1;
	if (lev % h == 0) n1 = nod;

	for (int j = 0; j < v[nod].size(); j++)
		Dfs(v[nod][j], n1, lev + 1);
}

int Lca(int x, int y)
{
	while (tata[x] != tata[y])
		if (niv[x] > niv[y]) x = tata[x];
		else y = tata[y];

	while (x != y)
		if (niv[x] > niv[y]) x = a[x];
		else y = a[y];

	return x;
}

int main()
{
    int x, y;

    fin >> n >> m;

	for (int i = 2; i <= n; i++)
	{
		fin >> a[i];// a[i] tata nodului i => muchia (a[i], i)
		v[a[i]].push_back(i);
	}

	Dfs(1,0,0);// dfs din nodul 1 care are radacina 0 si e la nivelul 0

	for (int i = 1; i <= m; i++)
	{
		fin >> x >> y;

		fout << Lca(x, y) << "\n";
	}

	fin.close(); fout.close();
	return 0;
}