Cod sursa(job #1875288)

Utilizator xtreme77Patrick Sava xtreme77 Data 10 februarie 2017 22:18:55
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <string>
#include <vector>

using namespace std ;

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

class DisjointDataSet {

	public :
	DisjointDataSet (int nn) 
	{
		n = nn ;
		tata.resize(n+1) ;
		rang.resize(n+1) ;
		for ( int i = 1 ; i <= n ; ++ i ) {
			tata [i] = i ;
			rang [i] = 1 ;
		}
	}
	void Unite (int x, int y) {
		unite(x,y);
	}
	string Solution (int x, int y)
	{
		if (FindFather(x) == FindFather(y)) {
			return "DA\n";
		}
		return "NU\n" ;
	}
	private :
	int n ;
	vector < int > tata ;
	vector < int > rang ;
	int FindFather (int x)
	{
		int R = x ; 
		while (x != tata[x]) {
			x = tata [x] ; 
		}
		while (R != tata[R]) {
			int aux = tata [R] ;
			tata[R] = x ;
			R = aux ;
		}
		return R ;
	}
	void unite (int x, int y)
	{
		x = FindFather (x) ; 
		y = FindFather (y) ;

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

int main()
{
	int n, m ;
	cin >> n >> m ;
	DisjointDataSet *D = new DisjointDataSet(n) ;
	while (m --) {
		int tip ;
		cin >> tip ;
		if (tip == 1) {
			int x, y ; 
			cin >> x >> y ;
			D -> Unite(x,y); 
		}
		else {
			int x, y ;
			cin >> x >> y ;
			cout << D -> Solution(x,y) ;
		}
	}
	return 0 ; 
}