Cod sursa(job #796731)

Utilizator danalex97Dan H Alexandru danalex97 Data 12 octombrie 2012 12:43:49
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>
using namespace std;

ifstream F("disjoint.in");
ofstream G("disjoint.out");

const int Nmax = 100010;

int Gr[Nmax],H[Nmax];
int N,M;
char Ans[3][10] = { "NU" , "DA" };

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

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

int main()
{
    F>>N>>M;
    for (int i=1;i<=N;++i)
        Gr[i]=i , H[i]=1;
    while ( M-- )
    {
        int type,a,b;
        F>>type>>a>>b;
        switch ( type )
        {
            case 1:
                Unite(a,b);
                break;
            case 2:
                G<<Ans[Comp(a)==Comp(b)]<<'\n';
                break;
        }
    }
    F.close();
    G.close();
    return 0;
}