Cod sursa(job #1680543)

Utilizator tqmiSzasz Tamas tqmi Data 8 aprilie 2016 20:48:35
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>
using namespace std;

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

const int NMax = 100005;
int TT[NMax],RG[NMax];
int N,M;

int Father(int x)
{
    while(x!=TT[x])
        x = TT[x];
    return x;
}

void Unite(int x, int y)
{
    if(RG[x] > RG[y])
        TT[y] = x;

    if(RG[x] < RG[y])
        TT[x] = y;

    if(RG[x] == RG[y])
    {
        TT[x] = y;
        RG[y]++;
    }

}

int main()
{
    fin>>N>>M;
    for(int i = 1; i<=N; i++)
        TT[i] = i;

    while(M--)
    {
        int op,x,y;
        fin>>op>>x>>y;
        if(op==1)
            Unite(Father(x),Father(y));
        if(op==2)
            {
                if(Father(x)==Father(y))
                    fout<<"DA\n";
                else
                    fout<<"NU\n";
            }

    }
    return 0;
}