Cod sursa(job #3239284)

Utilizator andrei_botorogeanuBotorogeanu Andrei andrei_botorogeanu Data 4 august 2024 10:36:05
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.3 kb
/*
Se dau N mulțimi de numere, inițial fiecare multime i conținând un singur element, mai exact elementul i. 
Asupra acestor mulțimi se pot face 2 tipuri de operații, astfel:

operatia de tipul 1: se dau două numere naturale x si y, între 1 si N. Se cere să reunească mulțimile ăn
care se află elementul x, respectiv elementul y (se garantează că x si y nu se vor afla in aceeași mulțime)
operatia de tipul 2: se dau două numere naturale x si y, între 1 si N. Se cere să afiseze DA dacă cele 2 
elemente se află în aceeași mulțime, respectiv NU în caz contrar.

input:
4 6
1 1 2
1 3 4
2 1 3
2 1 2
1 1 3
2 1 4
output:
NU
DA
DA
*/
#include <iostream>
#include <fstream>
#define FIN "disjoint.in"
#define FOUT "disjoint.out"
using namespace std;

typedef unsigned long ulong;

class UnionFind
{
public:
	UnionFind(ulong num): numElements( num ),
						  parent( new ulong[num+1] ),
						  Rank( new ulong[num+1] )
	{
		for(int i=1; i<=numElements; i++) {
			parent[i] = i;
			Rank[i] = 1;

		}	
	}	
	void UnionSets(ulong x, ulong y) {

		ulong rootX = getRoot( x );
		ulong rootY = getRoot( y );

		if( Rank[rootX] > Rank[rootY] ) {
	  
	  		parent[rootY] = rootX;
	
		} else if( Rank[rootX] < Rank[rootY] ) {
		
			parent[rootX] = rootY;
		
		} else {
			
			parent[rootX] = rootY;
			Rank[ rootY ] ++;

		}
	}

	ulong SameSets(ulong x, ulong y) {
		ulong rootX = getRoot( x );
		ulong rootY = getRoot( y );

		return rootX == rootY;
	}

	~UnionFind() {
		delete[] parent;
		delete[] Rank;
	}
private:
	ulong numElements,
		  *parent,
		  *Rank;

	ulong getRoot( ulong node ) {

		ulong root = parent[ node ];

		while(root != parent[ root ]) {
			root = parent[root];
		}
		return root;
	}

/*
	void updatePathRoot( ulong node, ulong root ) {

		if()
	}*/
};
int main(int argc, char const *argv[])
{
	ifstream fin(FIN);
	ofstream fout(FOUT);

	ulong numElements, // nr de multimi
		  numOps, // nr de operatii
		  type, // tipul operatiei
		  x, y;

	fin >> numElements >> numOps;
	UnionFind uf( numElements );
	
	while( numOps-- ) {
		
		fin >> type >> x >> y;
		switch( type ) 
		{
		case 1:
			uf.UnionSets(x, y);
			break;
		case 2:
			fout << (uf.SameSets(x, y) ? "DA" : "NU") << "\n";
		}
	}

	return 0;
}