Cod sursa(job #1605050)

Utilizator llalexandruLungu Alexandru Ioan llalexandru Data 18 februarie 2016 19:05:04
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>

using namespace std;

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

int TT[100001], RN[100001];

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

void unite(int x, int y)
{
    int aux;
    int rx=root(x);
    int ry=root(y);
    if (RN[rx]>RN[ry])
    {
        RN[rx] += RN[ry];
        TT[ry] = rx;
        while (TT[y]!=y)
        {
            aux=TT[y];
            TT[y]=rx;
            y=aux;
        }
    }
    else
    {
        RN[ry] += RN[rx];
        TT[rx] = ry;
        while (TT[x]!=x)
        {
            aux=TT[x];
            TT[x]=ry;
            x=aux;
        }
    }
}


int main()
{
    int n, m, i, caz, a, b;
    fin>>n>>m;
    for (i=1; i<=n; i++) TT[i]=i;
    for (i=1; i<=n; i++) RN[i]=1;
    for (i=1; i<=m; i++)
    {
        fin>>caz>>a>>b;
        if (caz==2)
        {
            if (root(a)==root(b))
                fout<<"DA"<<'\n';
            else
                fout<<"NU"<<'\n';
        }
        else
        {
            unite(a, b);
        }
    }
    return 0;
}