Cod sursa(job #676310)

Utilizator feelshiftFeelshift feelshift Data 8 februarie 2012 23:09:21
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
// http://infoarena.ro/problema/disjoint
#include <fstream>
using namespace std;

const int MAXSIZE = 100001;

ifstream in("disjoint.in");
ofstream out("disjoint.out");

int father[MAXSIZE],treeRank[MAXSIZE];

int numbers,operations,type,first,second;
void unite(int first,int second);
int find(int node);

int main() {
	in >> numbers >> operations;
	for(int i=1;i<=operations;i++) {
		in >> type >> first >> second;
		
		switch(type) {
			case 1: { unite(first,second); break; }
			case 2: { if(find(first) == find(second)) out << "DA\n"; else out << "NU\n"; break; }
		}
	}

	in.close();
	out.close();

	return (0);
}

void unite(int first,int second) {
	int firstRoot = find(first);
	int secondRoot = find(second);

	if(treeRank[firstRoot] < treeRank[secondRoot])
		father[firstRoot] = secondRoot;
	else
		father[secondRoot] = firstRoot;

	if(treeRank[firstRoot] == treeRank[secondRoot])
		treeRank[firstRoot]++;
}

int find(int node) {
	if(!father[node])
		return node;
	else
		return (father[node] = find(father[node]));
}