Cod sursa(job #1007464)

Utilizator otilia_sOtilia Stretcu otilia_s Data 8 octombrie 2013 22:32:06
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <cstdio>

using namespace std;
const int NMAX = 100020;
int rang[NMAX], tata[NMAX], n;

void init()
{
	for (int i = 1; i <= n; ++i) {
		tata[i] = i;
		rang[i] = 1;
	}
}

int find(int x) 
{
	int root = x;
	while (root != tata[root])
		root = tata[root];
	while (x != tata[x]) {
		int aux = tata[x];
		tata[x] = root;
		x = aux;
	}
	return root;
}

void unite(int x, int y) 
{
	if (rang[x] > rang[y])
		tata[y] = x;
	else {
		tata[x] = y;
		if (rang[x] == rang[y])
			++rang[y];
	}	
}

int main()
{
	int m;
	
	freopen("disjoint.in","r",stdin);
	freopen("disjoint.out","w",stdout);
	scanf("%d %d", &n, &m);
	
	init();

	for (int i = 0; i < m; ++i) {
		int x, y, op;
		scanf("%d %d %d", &op, &x, &y);
		if (op == 1) 
			unite(find(x), find(y));
		else
			printf(find(x) == find(y) ? "DA\n" : "NU\n");
	}
	return 0;
}