Cod sursa(job #272764)

Utilizator 630r63Ilinca George Mihai 630r63 Data 7 martie 2009 19:27:51
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <cstdio>
#include <cstdlib>

class Set
{
	private : int *t;

	public : Set(int size)
	{
		t = (int *) calloc(size, sizeof(int));
	}

	public : void Union(int x, int y)
	{
		int tx = x, tmp;
		while (t[tx]) tx = t[tx];
		while (t[x] != tx && x != tx) { tmp = t[x]; t[x] = tx; x = tmp;	}
		while (y) { tmp = t[y]; t[y] = tx; y = tmp; }
	}

	public : int Query(int x, int y)
	{
		int tx = x, ty = y, tmp;
		while (t[tx]) tx = t[tx];
		while (t[ty]) ty = t[ty];
		while (t[x] != tx && x != tx) { tmp = t[x]; t[x] = tx; x = tmp; }
		while (t[y] != ty && y != ty) { tmp = t[y]; t[y] = ty; y = tmp; }
		return tx == ty?1:0;
	}
};

int N, M, x, y, o;

int main()
{
	freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);
	scanf("%d %d\n", &N, &M);
	for ( Set set(N+1); M; --M)
	{
		scanf("%d %d %d\n", &o, &x, &y);
		if (o-1) printf("%s\n", set.Query(x,y)?"DA":"NU");
		else set.Union(x,y);
	}
	return 0;
}