Cod sursa(job #962997)

Utilizator gabrieligabrieli gabrieli Data 16 iunie 2013 12:21:43
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;

// Maximum number of sets.
const size_t MAXN = 100010;
/* Array which holds the sets information as a forrest of trees.
 * The root of the tree is the representative of the set.
 */
size_t sets_forest[MAXN];
// Array which is used to perform the path-compresion heuristic.
size_t height_set[MAXN];

void init(size_t n) 
{
	for (size_t i = 0; i <= n; ++i)
	{
		sets_forest[i] = i;
		height_set[i] = 0;
	}
}

// Finds the representative/name os the set to which s belongs to.
size_t find_set(size_t s)
{
	if (sets_forest[s] != s)
		sets_forest[s] = find_set(sets_forest[s]);
	return sets_forest[s];
}

// Performs the union of the sets containing elements s1 and s2.
void union_sets(size_t s1, size_t s2)
{
	s1 = find_set(s1);
	s2 = find_set(s2);

	if (s1 != s2)
	{
		if (height_set[s1] > height_set[s2])
			sets_forest[s2] = s1;
		else if (height_set[s1] < height_set[s2])
			sets_forest[s1] = s2;
		else
		{
			sets_forest[s2] = s1;
			height_set[s1]++;
		}
	}
}

int main()
{
	ifstream fin ("disjoint.in");
	ofstream fout ("disjoint.out");

	int N, m;
	fin >> N >> m;

	init(N);

 	for (; m; --m)
	{
		int op, x, y;
		fin >> op >> x >> y;
		if (op == 1) union_sets (x, y);
		else if (find_set(x) == find_set(y))
			fout << "DA\n";
		else
			fout << "NU\n";
	}
 
	fout.close();
	return EXIT_SUCCESS;
}