Cod sursa(job #2226047)

Utilizator AraldaAralda Pacurar Aralda Data 29 iulie 2018 13:51:23
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

typedef struct node {

	int key;
	struct node* parent;
	int rank;

}node;

node* nodes[100001];

node* make_set(int key) {

	node* n = (node *)malloc(sizeof(node));
	if (n == NULL) {

		perror("malloc failed");
		exit(1);
	}

	n->key = key;
	n->parent = n;
	n->rank = 0;

	return n;
}

node* find_set(node* x) {

	if (x->parent != x) {

		x->parent = find_set(x->parent);
	}

	return x->parent;
}

void link(node* x, node* y) {

	if (x->rank > y->rank) {

		y->parent = x;
	}
	else if (y->rank > x->rank) {

		x->parent = y;
	}
	else {

		x->parent = y;
		y->rank = y->rank + 1;
	}
}

void unite(node* x, node* y) {

	link(x, y);
}

int main() {

	FILE* ip;
	ip = fopen("disjoint.in", "r");
	if (ip == NULL) {

		perror("Could not open input file");
		return 1;
	}

	FILE* op;
	op = fopen("disjoint.out", "w");
	if (op == NULL) {

		perror("Could not open output file");
		return 1;
	}

	int n, m;
	fscanf(ip, "%d%d", &n, &m);

	for (int i = 1; i <= n; i++) {

		nodes[i] = make_set(i);
	}

	for (int i = 0; i < m; i++) {

		int cod, x, y;
		fscanf(ip, "%d%d%d", &cod, &x, &y);

		if (cod == 1) {

			unite(nodes[x], nodes[y]);
		}
		else if (cod == 2) {

			if ((find_set(nodes[x]))->key == (find_set(nodes[y]))->key) {

				fprintf(op, "DA\n");
			}
			else {

				fprintf(op, "NU\n");
			}
		}
	}

	fclose(ip);
	fclose(op);

	return 0;
}