Cod sursa(job #701615)

Utilizator avram_florinavram florin constantin avram_florin Data 1 martie 2012 16:47:54
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include<fstream>
#include<cstdio>

using namespace std;

const int MaxN = 100001;

const char InFile[] = "disjoint.in";
const char OutFile[] = "disjoint.out";

int N,M,R[MaxN],T[MaxN];

int find(int x)
{
	int y,rad;
	rad = x;
	while( T[rad] != rad )
		rad = T[rad];
	while( x != T[x] )
		{
			y = T[x];
			T[x] = rad;
			x = y;
		}
	return rad;
}

void unire(int x,int y)
{
	if( R[x] <= R[y] )
		T[x] = y;
		else
		T[y] = x;
	if( R[x] == R[y] )
		++R[y];
}

int main()
{
	ifstream fin( InFile );
	ofstream fout( OutFile );
	int tip,i,x,y;
	fin >> N >> M;
	for( i = 1 ; i <= N ; ++i )
		{
			T[i] = i;
			R[i] = 1;
		}
	for( i = 0 ; i < M ; ++i )
		{
			fin >> tip >> x >> y;
			if( tip == 1 )
				unire(find(x),find(y));
				else
				if( find(x) == find(y) )
					fout << "DA\n";
					else
					fout << "NU\n";
		}
	return 0;
}