Cod sursa(job #254812)

Utilizator willliIonel Bratianu willli Data 7 februarie 2009 17:27:22
Problema Paduri de multimi disjuncte Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.26 kb
#include <stdio.h>
#include <stdlib.h>
#define MAX 100001
#define in "disjoint.in"
#define out "disjoint.out"

struct el_mult
{
	int parent, height;
};

struct el_mult set[MAX];

int find_parent(int x)
{	
	if (set[x].parent == 0)
		return x;
	else
	{
		set[x].parent = find_parent(set[x].parent);
		return set[x].parent;
	}
}

void reunion(int x, int y)
{
	int px, py;
	px = find_parent(x);
	py = find_parent(y);
	if (set[px].height < set[py].height)
	{
		set[px].parent = py;
	} else if (set[px].height > set[py].height)
	{
		set[py].parent = px;
	} else if (px != py)
	{
		set[py].parent = px;
		set[px].height++;
	}
}


int find(int x, int y)
{
	int px, py;
	px = find_parent(x);
	py = find_parent(y);
	
	return px == py;
}

int main()
{
	int i, z, m, n, x, y;
	FILE *fin, *fout;
	
	if ((fin = fopen(in, "r")) == NULL)
	{
		printf("Eroare \n");
		exit(-1);
	}
	//read dimension of vectors
	fscanf(fin, "%d%d", &n, &m);

	//read the vectors
	for (i = 1; i<=n ; i++)
	{
		set[i].parent = 0;
		set[i].height = 0;
	}
	
	fout = fopen(out, "w");

	for (i = 0; i < m; i++)
	{
		fscanf(fin, "%d%d%d", &x, &y, &z);
		if (x == 1)
		{
			reunion(y, z);
		}
		else if (x == 2)
		{
			z = find(y, z);
			fprintf(fout, "%s\n", z == 0 ? "NU" : "DA");
		}
	}
	fclose(fin);
	fclose(fout);
	return 0;
}