Cod sursa(job #796770)

Utilizator danalex97Dan H Alexandru danalex97 Data 12 octombrie 2012 15:24:23
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],N,M;
const char Ans[3][5] = { "NU\n" , "DA\n" , "" };

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()
{
    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<<( Comp(a)==Comp(b) ?"DA":"NU" )<<'\n';
                break;
        }
    }
    F.close();
    G.close();
    return 0;
}