Cod sursa(job #633382)

Utilizator andumMorie Daniel Alexandru andum Data 13 noiembrie 2011 18:13:19
Problema Paduri de multimi disjuncte Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>

using namespace std;

const int nmax = 100005;
int tata[nmax], niv[nmax], radacina_x, radacina_y;

int root(int x)
{
	int aux=x, nv=0, radacina;
	
	aux=x;
	while (tata[x]!=x)
	{
		x=tata[x];
		++nv;
	}
	radacina=x;
	x=aux;
	while (tata[x]!=x)
	{
		tata[x]=radacina;
		niv[x]=nv;
		x=tata[x];
	}
		
	return radacina;
}

void merge(int x, int y)
{
	if (niv[x] >= niv[y])
		tata[y]=radacina_x;
	else
		tata[x]=radacina_y;
}

int main()
{
	int N, M, op, x, y;
	
	ifstream f("disjoint.in");
	ofstream g("disjoint.out");
	
	f>>N>>M;
	for (int i=1; i<=N; ++i)
		tata[i]=i;
	for (; M; --M)
	{
		f>>op>>x>>y;
		radacina_x=root(x);
		radacina_y=root(y);
		
		if (op == 1)
			merge(x,y);
		else
			if (radacina_x == radacina_y)
				g<<"DA\n";
			else 
				g<<"NU\n";
	}

	return 0;
}