Cod sursa(job #703801)

Utilizator Catah15Catalin Haidau Catah15 Data 2 martie 2012 14:35:01
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

#define maxN 100010

int tata[maxN], H[maxN];


int root (int X)
{
	int R;
	
	for (R = X; R != tata[R]; R = tata[R]);
	for (int y; X != tata[X]; y = tata[X], tata[X] = R, X = y);
	
	return R;
}


void Unite (int X, int Y)
{
	int Rx = root (X);
	int Ry = root (Y);
	
	if (H[Rx] > H[Ry]) tata[Ry] = Rx;
	else tata[Rx] = Ry;
	
	if (H[Rx] == H[Ry]) ++ H[Ry];
}

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;
	
	while (M --)
	{
		int cod, x, y;
		
		scanf ("%d %d %d", &cod, &x, &y);
		
		if (cod == 1) Unite (x, y);
		else if (root (x) == root (y)) printf ("DA\n");
		else printf ("NU\n");
	}
	
	return 0;
}