Cod sursa(job #2041974)

Utilizator Spiromanii_MessiUNIBUCThrowTerror Spiromanii_Messi Data 17 octombrie 2017 22:09:34
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <vector>

using namespace std ;

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

class DDSet
{
public:
	int n ;
	vector <int> tata ;
	vector <int> rang ; 
	DDSet(int n){
		this -> n = n ; 
		tata.resize (n + 1) ; 
		rang.resize (n + 1) ;
		for (int i = 1 ; i <= n ; ++ i) {
			rang [i] = 1 ;
			tata [i] = i ; 
		} 
	}
	int Father (int nod) {
		int R = nod ; 
		while (R != tata [R]) {
			R = tata [R] ; 
		}
		while (nod != tata [nod]) {
			int aux = tata [nod] ; 
			tata [nod] = R ; 
			nod = aux ; 
		}
		return R ; 
	}	
	void Unite (int x, int y) {
		x = Father (x) ; 
		y = Father (y) ; 

		if (x == y) return ; 

		if (rang [x] < rang [y]) {
			swap (x, y) ; 
		}
		rang [x] += rang [y] ; 
		tata [y] = tata [x] ;
	}
};

int main(int argc, char const *argv[])
{
	int n ; 
	cin >> n ; 
	int m ; 
	cin >> m ;
	DDSet *D = new DDSet (n) ; 
	while (m --) {
		int t ;
		cin >> t ; 
		if (t == 1) {
			int a, b ;
			cin >> a >> b ; 
			D -> Unite (a, b) ; 
		}
		else {
			int a, b; 
			cin >> a >> b ; 
			if (D -> Father (a) == D -> Father (b)) {
				cout << "DA\n" ; 
			}
			else {
				cout << "NU\n" ; 
			}
		}
	}
	return 0;
}