Cod sursa(job #2934615)

Utilizator widzAndrei-Daniel Tava widz Data 6 noiembrie 2022 10:35:20
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <iostream>
using namespace std;

template <typename T>
class DisjointForest{
private:
	const unsigned int _size;
	T* _father;

	T getRoot(T el){
		while(_father[el - 1] != el){
			el = _father[el - 1];
		}
		return el;
	}
public:
	DisjointForest(const unsigned int p_size) : _size(p_size){
		_father = new T[p_size];

		for(unsigned int i = 0; i<p_size;++i){
			_father[i] = i + 1;
		}
	}
	void merge(const T x, const T y){
		_father[getRoot(y) - 1] = getRoot(x);
	}

	bool check(const T x, const T y){
		return getRoot(x) == getRoot(y);
	}
	~DisjointForest(){
		delete[] _father;
	}
};

int main(){
	ifstream in("disjoint.in");
	ofstream out("disjoint.out");
	unsigned int n, m;
	in >> n >> m;
	DisjointForest<unsigned int> forest(n);
	for(unsigned int i=0; i<m; ++i){
		unsigned int cmd, x, y;
		in >> cmd >> x >> y;
		switch(cmd)
		{
		case 1:
			forest.merge(x, y);
			break;

		case 2:
			out << (forest.check(x, y) ? "DA\n" : "NU\n");
			break;

		default:
			break;
		}
	}
	in.close();
	out.close();
}