Cod sursa(job #262823)

Utilizator ErgoVicol Sergiu Constantin Ergo Data 19 februarie 2009 18:02:55
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <fstream>

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

#define NMAX 100005

int P[NMAX], S[NMAX], N, M;

int findNod (int x)
{
        int R, y;

        for (R = x; P[R] != R; R = P[R]);  //Cautare Radacina

        for (; x != R;)                   //Compresie Arbore
        {
                y = P[x];
                P[x] = R;
                x = y;
        }
        return R;
}
void mergeTr (int x, int y)
{
        if (S[x] > S[y]) P[y] = x;
        else P[x] = y;
        if (S[x] == S[y])
                S[y] ++;
}
int main()
{
        int p, x, y, i;
        fin >>N >>M;

        for (i = 1; i <= N; i++)
                P[i] = i;

        for (i = 1; i <= M; i++)
        {
                fin >>p >>x >>y;
                x = findNod(x);
                y = findNod(y);
                if (p == 2)
                        if (x == y) fout <<"DA\n"; else fout<<"NU\n";
                if (p == 1)
                        mergeTr(x,y);
        }
        fout.close();
        return 0;
}