Cod sursa(job #742261)

Utilizator teodora.petrisorPetrisor Teodora teodora.petrisor Data 29 aprilie 2012 10:46:17
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <stdio.h>

#define NMAX 100002

int TT[NMAX], RG[NMAX];
int N, M;

int find(int x)
{
	int R, y;
	
	// go up the tree until we find a node that points to itself
	for(R = x; TT[R] != R; R = TT[R]);
	
	// apply road compression so we get better run time
	for(; TT[x] != x;)
	{
		y = TT[x];
		TT[x] = R;
		x = y;
	}
	
	return R;
}

void unite(int x, int y)
{
	// unite the set with smaller rank to the one with bigger rank
	if(RG[x] > RG[y])
		TT[y] = x;
	else
		TT[x] = y;
	
	// if ranks were equal, raise the rank of the new set with 1
	if(RG[x] == RG[y])
		RG[y] ++;
}

int main()
{
	FILE* f, g;
	f = freopen("disjoint.in", "r", stdin);
	g = freopen("disjoint.out", "w", stdout);
	
	scanf("%d %d", &N, &M);		// read the number of sets and the number of operations
	
	int i, x, y, cd;
	
	
	// at first every node points to itself and every tree has rank 1
	for(i = 1; i <= N; i++)
	{
		TT[i] = i;		// every node points to itself
		RG[i] = 1;		// every tree has rank = 1
	}
	
	for(i = 1; i<=M; i++)	// read the operations
	{
		scanf("%d %d %d", &cd, &x, &y);
		
		if(cd == 2)			// if we have to check whether they are in the same tree
		{
			if(find(x) == find(y))	// check and write appropriate message
				printf("DA\n");
			else
				printf("NU\n");
		}
		
		else		// if we have to unite two trees
		{
			if(find(x) == find(y))	// if they are in the same tree, it is an error
			{
				fprintf(stderr, "%d ", i);
				return 0;
			}
			unite(find(x), find(y));	// if they are in disjoint trees, we unite them
		}
	}
	
	
	fclose(stdin);
	fclose(stdout);

	return 0;
}