Cod sursa(job #323013)

Utilizator GulyanAlexandru Gulyan Data 10 iunie 2009 15:53:36
Problema Paduri de multimi disjuncte Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 0.91 kb
#include <stdio.h>
#include <stdlib.h>

typedef int *Set;

Set newSet(int n)
{
	Set S = (Set)calloc( (n + 1), sizeof(int));
	return S;
}

void deleteSet( Set S)
{
	if(S == NULL)
		return;
	free( S );
	S = NULL;
}

int findSet(Set S, int x)
{
	if(S[x] <= 0)
		return x;
	return S[x] = findSet(S, S[x]);//compresia caii
}

void unionSet(Set S, int x, int y)
{
	x = findSet(S, x);
	y = findSet(S, y);
	if(x == y)
		return;
	if(-S[x] > -S[y])
		S[y] = x;
	else{
		if(S[x] == S[y])
			S[y]--;
		S[x] = y;
	}
}

char *REZ[] = {"NU", "DA"};

int main()
{
	freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);
	int n, m, c, x, y;
	scanf("%d %d", &n, &m);
	Set S = newSet( n );
	
	for(;m--;){
		scanf("%d %d %d", &c, &x, &y);
		if(c == 1)
			unionSet(S, x, y);
		else
			printf("%s\n", REZ[findSet(S, x) == findSet(S, y)]);
	}
	
	deleteSet( S );
	return 0;
}