Cod sursa(job #291039)

Utilizator stefysStefan stefys Data 29 martie 2009 12:00:40
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
using namespace std;

class DisjointSets {
public:
	DisjointSets (unsigned int size) : size(size), info(new Info[size])
	{ for (unsigned int i=0; i<size; ++i) info[i].parent = i, info[i].rank = 0; }
	void unionSets (unsigned int x, unsigned int y);
	unsigned int findSet (unsigned int x);
private:
	struct Info {
		unsigned int parent;
		unsigned int rank;
	} *info;
	unsigned int size;
};

int main ()
{
	ifstream in("disjoint.in");
	ofstream out("disjoint.out");
	unsigned int N, M;
	
	in >> N >> M;
	DisjointSets disjointSets(N);
	for (unsigned int i=0; i<M; ++i) {
		unsigned int op,x,y;
		in >> op >> x >> y;
		--x; --y;
		if (op == 1) disjointSets.unionSets(x,y);
		else out << ((disjointSets.findSet(x) == disjointSets.findSet(y)) ? "DA\n" : "NU\n");
	}
	in.close();
	out.close();
	return 0;
}

void DisjointSets::unionSets (unsigned int x, unsigned int y)
{
	unsigned int xRoot = findSet(x), yRoot = findSet(y);
	if (info[xRoot].rank < info[yRoot].rank)
		info[yRoot].parent = xRoot;
	else if (info[xRoot].rank > info[yRoot].rank)
		info[xRoot].parent = yRoot;
	else if (xRoot != yRoot) {
		info[yRoot].parent = info[xRoot].parent;
		++info[xRoot].rank;
	}
}
unsigned int DisjointSets::findSet (unsigned int x)
{
	if (info[x].parent == x) return x;
	info[x].parent = findSet(info[x].parent);
	return info[x].parent;
}