Cod sursa(job #1195472)

Utilizator informatician28Andrei Dinu informatician28 Data 7 iunie 2014 13:06:12
Problema Paduri de multimi disjuncte Scor 20
Compilator c Status done
Runda Arhiva educationala Marime 1.33 kb
#include <stdio.h>
#include <stdlib.h>

#define DIM 100001

typedef enum op {
	toUnite = 1,
	toQuery
} operationCode;

void unite(int x, int y, int *Rank, int *Father)
{
	// apply here the rank heuristics
	if (Rank[x] > Rank[y])
		Father[y] = x;
	else 
		Father[x] = y;
	if (Rank[x] == Rank[y])
			Rank[x]++;
}

int find(int x, int *Rank, int *Father)
{
	int R;
	for (R = Father[x]; R != Father[R]; R = Father[R]);
	// apply here the road heuristics
	for (; x != Father[x];) {
		int y = Father[x];
		Father[x] = R;
		x = y;
	}
	return R;
}

void freeMemory(int *Rank, int *Father)
{
	free(Rank);
	free(Father);
}

int main()
{
	freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);

	int *Father, *Rank, N, M, i, x, y;
	Father = (int*)malloc(DIM * sizeof(int));
	Rank = (int*)malloc(DIM * sizeof(int));

	scanf("%d%d", &N, &M);
	
	for (i = 1; i <= N; i++) {
		Father[i] = i; // every node first will point to itself
		Rank[i] = 1; // the rank will be 1 for all the trees, at the beginning, it also can be 0
	}

	int operation;
	for (i = 1; i <= M; i++) {
		scanf("%d%d%d", &operation, &x, &y);
		if (operation == toUnite) {
			unite(x, y, Rank, Father);
		}	
		else if (operation == toQuery) {
			if (find(x, Rank, Father) == find(y, Rank, Father))
				printf("DA\n");
			else 
				printf("NU\n");
		}
	}
	freeMemory(Rank, Father);
	return 0;
}