Cod sursa(job #669527)

Utilizator cahemanCasian Patrascanu caheman Data 27 ianuarie 2012 10:59:44
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.69 kb
#include<stdio.h>
long n,m;
long t[100005];
long h[100005];
long find(long x)
{
	int i=x;
	while(i!=t[i])
	{
		i=t[i];
	}
	return i;
}
void mica_unire(long a,long b)
{
	int x,y;
	x=find(a);
	y=find(b);
	if(h[x]==h[y])
	{
		h[x]++;
		t[y]=x;
	}
	else
	{
		if(h[x]>h[y])
			t[y]=x;
		else
			t[x]=y;
	}
}
int main()
{
	freopen("disjoint.in","r",stdin);
	freopen("disjoint.out","w",stdout);
	long i,a,b,c;
	scanf("%ld%ld",&n,&m);
	for(i=1;i<=n;i++)
		t[i]=i;
	for(i=1;i<=m;i++)
	{
		scanf("%ld%ld%ld",&a,&b,&c);
		if(a==1)
		{
			mica_unire(b,c);
		}
		else
		{
			if(find(b)==find(c))
				printf("DA\n");
			else
				printf("NU\n");
		}
	}
	return 0;
}