Cod sursa(job #796794)

Utilizator danalex97Dan H Alexandru danalex97 Data 12 octombrie 2012 15:51:08
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.82 kb
#include <fstream>
using namespace std;

const int Nmax = 100010;

int Gr[Nmax],H[Nmax],N,M;

int Comp(int x)
{
	int R, y;
	for ( R = x; Gr[R] != R; R = Gr[R] );
	for ( ; Gr[x] != x ; )
	{
	    y = Gr[x];
        Gr[x] = R;
        x = y;
	}
	return R;
}

void Unite(int a,int b)
{
    if( H[a] > H[b])
		Gr[b] = a;
	else
		Gr[a] = b;
	if (H[a] == H[b])
        ++H[b];
}

int main()
{
    freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);
    scanf("%d %d",&N,&M);

    for (int i=1;i<=N;++i)
        Gr[i]=i , H[i]=1;
    while ( M-- )
    {
        int type,a,b;
        scanf("%d %d %d",&type,&a,&b);
        if (type == 1)
            Unite(Comp(a),Comp(b));
        else
            printf("%s\n",( Comp(a)==Comp(b) ?"DA":"NU" ));
    }
    return 0;
}