Cod sursa(job #646202)

Utilizator belginstirbuasdf asdf belginstirbu Data 11 decembrie 2011 08:50:10
Problema Paduri de multimi disjuncte Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.29 kb
#include <stdio.h>
#include <stdlib.h>

unsigned int N, M, *parent, *heights;

unsigned int findRoot(unsigned int x)
{
	unsigned int root, temp, tempParent;

	temp = x;
	while(parent[temp])
		temp = parent[temp];

	root = temp; temp = x;

	while(parent[temp])
	{
		tempParent = parent[temp];
		parent[temp] = root;
		temp = tempParent;
	}

	return root;
}

void op1(unsigned int x, unsigned int y)
{
	unsigned int rx = findRoot(x);
	unsigned int ry = findRoot(y);
	
	if(heights[rx] > heights[ry])
		parent[ry] = rx;
	else if(heights[rx] < heights[ry])
	{
		parent[rx] = ry;
	}
	else
	{
		++heights[rx];
		parent[ry]= rx;
	}
}

short op2(unsigned int x, unsigned int y)
{
	return findRoot(x) == findRoot(y);
}

int main()
{
	unsigned int op, x, y, i;
	freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);
	
	scanf("%u %u", &N, &M);
	parent = (unsigned int*)malloc(sizeof(unsigned int) * (N + 1));
	heights = (unsigned int*)malloc(sizeof(unsigned int) * (N + 1));
	
	for(i = 1; i <= N; ++i)
		parent[i] = heights[i] = 0;
	
	while(M--)
	{
		scanf("%u %u %u", &op, &x, &y);

		switch(op)
		{
		case 1:
			op1(x, y);
			break;
		case 2:
			if(op2(x, y))
				puts("DA");
			else
				puts("NU");
			break;
		}
	}
	
	return 0;
}