Cod sursa(job #1161155)

Utilizator ArmandNMArmand Nicolicioiu ArmandNM Data 31 martie 2014 02:57:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>

const int NMAX = 100005;

using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");

int N,M,TT[NMAX],RG[NMAX],x,y,cod;

int find(int nod)
{
    int R = nod,y;
    for (; R != TT[R]; R = TT[R]);

    for (;TT[nod] != nod;)
    {
        y = TT[nod];
        TT[nod] = R;
        nod = y;
    }

    return R;
}

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

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

int main()
{
    f >> N >> M;

    for (int i = 1; i <= N; ++i)
    {
        RG[i] = 1;
        TT[i] = i;
    }

    for (int i = 1; i <= M; ++i)
    {
        f >> cod >> x >> y;
        if (cod == 2)
        {
            if (find(x) == find(y))
                g << "DA" << '\n';
            else g << "NU" << '\n';
        }
        if (cod == 1)
        {
            unite(find(x),find(y));
        }
    }

    f.close();
    g.close();
    return 0;
}