Cod sursa(job #1693435)

Utilizator cpitting_llamasRotaru Tanase Gherghina cpitting_llamas Data 23 aprilie 2016 01:58:48
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <cstdio>

//using namespace std;

class disjoint_sets {
private:
	unsigned *parents;
	unsigned *set_identifier;
	unsigned forest_size;

public:
	disjoint_sets(unsigned size)
		: forest_size(size)
	{
		parents = new unsigned[size];
		set_identifier = new unsigned[size];

		for (unsigned idx = 1; idx <= forest_size; ++idx) {
			parents[idx] = idx;
			set_identifier[idx] = 1;
		}
	}
	
	~disjoint_sets()
	{
		delete [] parents;
		delete [] set_identifier;
	}

	unsigned find_set_of(unsigned elem)
	{
		unsigned root = 0;
		unsigned temp = 0;
		
		if (elem > forest_size)
			return root;
		/*find the root of the set*/
		for(root = elem; parents[root] != root; root = parents[root]);

		/*compress the paths*/
		while(parents[elem] != elem)
		{
			temp = parents[elem];
			parents[elem] = root;
			elem = temp;
		}
		return root;
	}

	void merge_sets_of_elems(unsigned e1, unsigned e2)
	{
		if (find_set_of(e1) == find_set_of(e2))
			return;

		if (set_identifier[e1] > set_identifier[e2])
			parents[e2] = e1;
		else
			parents[e1] = e2;
		
		if (set_identifier[e1] == set_identifier[e2])
			++set_identifier[e2];
	}
};

int main() {
	std::ifstream cin("disjoint.in");
	std::ofstream cout("disjoint.out");
	
	disjoint_sets dsets(10001);
	unsigned N;
	unsigned M;
	
	cin >> N >> M;	
		
	for (unsigned i = 0; i < M; ++i) {
		unsigned comm, arg1, arg2;
		cin >> comm >> arg1 >> arg2;
		if (2 == comm) {
			if (dsets.find_set_of(arg1) == dsets.find_set_of(arg2))
				cout << "DA\n";
			else
				cout << "NU\n";

		} else
			dsets.merge_sets_of_elems(arg1, arg2);
		
	}
	return 0;
}