Cod sursa(job #792913)

Utilizator alex_unixPetenchea Alexandru alex_unix Data 1 octombrie 2012 16:40:37
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb

#include <cstdio>

const int MAX_SIZE(100001);

int forest [MAX_SIZE];

// Because sets are numbered starting from 1, I can count the depth of each tree
// and skip the -1 initialization, but I choosed to solve the general case though

inline void initialize (int n)
{
	for (int *iterator(forest + 1), *end(forest + n) ; iterator <= end ; ++iterator)
		*iterator = -1;
}

int find_set (int x)
{
	if (forest[x] < 0)
		return x;
	forest[x] = find_set(forest[x]); // path compression
	return forest[x];
}

inline void set_union (int x, int y)
{
	x = find_set(x);
	y = find_set(y);
	if (x == y)
		return;
	if (forest[y] < forest[x])
	{
		x ^= y;
		y ^= x;
		x ^= y;
	}
	forest[x] += forest[y];
	forest[y] = x;
}

int main (void)
{
	std::freopen("disjoint.in","r",stdin);
	std::freopen("disjoint.out","w",stdout);
	int n, m;
	std::scanf("%d%d",&n,&m);
	initialize(n);
	char operation, *operation_ptr(&operation);
	int x, *x_ptr(&x), y, *y_ptr(&y);
	do
	{
		std::scanf("\n%c%d%d",operation_ptr,x_ptr,y_ptr);
		if (operation == '1')
			set_union(x,y);
		else
			std::printf("%s\n",(find_set(x) == find_set(y) ? "DA" : "NU"));
		--m;
	}
	while (m);
	std::fclose(stdin);
	std::fclose(stdin);
	return 0;
}