Cod sursa(job #677778)

Utilizator marius135Dumitran Adrian Marius marius135 Data 10 februarie 2012 17:30:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
// Infoarena - Arhiva Educationala Multimi Disjuncte
// Februrie 2012 Marius Dumitran
// implementare clasica O(M * log*N)

#include<string.h>
#include<stdio.h>
#include<vector>
#define maxn 100001
#define maxm 100001

using namespace std;

int tata[ maxn ], size[ maxn ];

void arhive(int nod) {
	int temp_nod = nod;
	while (tata[ temp_nod ] != temp_nod)
		temp_nod = tata[ temp_nod ];
	int tati = temp_nod;
	while (tata[ nod ] != nod)  {
		temp_nod = tata[ nod ];
		tata[ nod ] = tati;
		nod = temp_nod;
	}
}

void comp( int nod1, int nod2) {
	
	arhive (nod1);
	arhive (nod2);
	if (tata[nod1] == tata[nod2]) printf("DA\n");
	else printf("NU\n");
}
void join( int nod1, int nod2) {
	arhive (nod1);
	arhive (nod2);
	int tata1 = tata[nod1], tata2 = tata[nod2];
	if( size[ tata1 ] > size[tata2] )
		tata1 = tata1 ^ tata2 ^(tata2 = tata1);
	size[ tata2 ] += size[ tata1 ];
	tata[ tata1 ] = tata2;
}


int main(){
	
	freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);
	int n, m;
	scanf("%d %d", &n, &m);
	for( int i = 1; i <= n; ++i) 
		tata[i] = i, size[i] = 1;
	for( int i = 1; i <= m; ++i) {
		int a, b, c;
		scanf("%d %d %d", &a, &b, &c);
		if( a == 1 ) {
			join (b, c);
		}
		if( a == 2 ) {
			comp (b, c);
		}
		
	}
}