Cod sursa(job #374127)

Utilizator klamathixMihai Calancea klamathix Data 15 decembrie 2009 23:35:31
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
#include<cstdio>
#define maxn 100005
int i , j , k , n , m , a , b , type;

int dad[maxn] , rang[maxn];

void unite ( int x , int y )
{
	if ( rang[x] > rang[y] ) 
		dad[y] = x;
	else
		dad[x] = y;
	
	if ( rang[x] == rang[y] ) rang[y] ++;
}
	
int find ( int x ) 
{
	int root , y;
	
	for( root = x ; root != dad[root] ; root = dad[root] );
	
	for ( ; dad[x] != x ;) 
	{
		y = dad[x];
		dad[x] = root;
		x = y;
	}

return root;
}

int main()
{
	freopen("disjoint.in","r",stdin);
	freopen("disjoint.out","w",stdout);
	
	scanf("%d %d",&n,&m);
	
	for( i = 1 ; i <= n ; ++i )
	{
		dad[i] = i;
		rang[i] = 1;
	}
	
	for ( i = 1 ; i <= m ; ++i )
	{
		scanf("%d %d %d",&type,&a,&b);
		
		if ( type == 1 ) 
			unite ( find ( a ) , find ( b ) ) ;
		
		else if ( type == 2 )
		{
			if ( find ( a ) == find ( b ) ) printf("DA\n");
			else printf("NU\n");
		}
	}
	
return 0;
}