Cod sursa(job #565383)

Utilizator andra23Laura Draghici andra23 Data 27 martie 2011 18:26:13
Problema Lowest Common Ancestor Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <vector>

using namespace std;

const int maxn = 100010;
const int maxm = 2000010;
int t[maxn], viz[maxn], ancestor[maxn], rang[maxn];
vector < pair <int,int> > q[maxn];
vector <int> v[maxn];
int res[maxm];

int f_find(int nod) {
	int x = nod, y;
	while (x != t[x]) {
		x = t[x];	
	}
	while (nod != t[nod]) {
		y = t[nod];
		t[nod] = x;
		nod = y;
	}
	return x;
}

void f_union(int p, int q) {
	p = f_find(p);
	q = f_find(q);
	if (rang[p] < rang[q]) 
		t[p] = q;	
	else 
		if (rang[q] < rang[p]) 
			t[q] = p;
		else { 
			t[q] = p;
			rang[p]++;	
		}
}

void dfs(int nod) {
	t[nod] = nod;
	ancestor[nod] = nod;
	for (int i = 0; i < v[nod].size(); i++) {
		dfs(v[nod][i]);
		f_union(nod, v[nod][i]);
		ancestor[f_find(nod)] = nod;
	}	
	viz[nod] = 1;
	for (int i = 0; i < q[nod].size(); i++) {
		int x = q[nod][i].first;
		if (viz[x] == 1) 
			res[q[nod][i].second] = ancestor[f_find(x)];	
	}
}

int main() {
	ifstream f("lca.in");
	ofstream g("lca.out");	
	
	int n, m;
	f >> n >> m;
	
	int i, j, k, x, y, a, b;
	t[1] = -1;
	for (i = 2; i <= n; i++) {
		f >> x;
		v[x].push_back(i);	
	}
	
	for (i = 1; i <= m; i++) {
		f >> a >> b;
		q[a].push_back(make_pair(b, i));
		q[b].push_back(make_pair(a, i));
	}
	
	dfs(1);
	
	for (i = 1; i <= m; i++)
		g << res[i] << '\n';
	
	return 0;
}