Cod sursa(job #623107)

Utilizator Catah15Catalin Haidau Catah15 Data 19 octombrie 2011 09:36:54
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <cstdio>

using namespace std;

#define maxN 100005

int tata[maxN], H[maxN];


int root (int x)
{
	int y = x, R;
	
	for (R = x; tata[R] != R; R = tata[R]);
	
	while (tata[x] != 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 type, x, y;
		
		scanf ("%d %d %d", &type, &x, &y);
		
		if (type == 1) unite (x, y);
		else 
			if (root (x) == root (y)) printf ("DA\n");
		else printf ("NU\n");
	}
	
	return 0;
}