Cod sursa(job #3235493)

Utilizator bogdan1479Luca Bogdan Alexandru bogdan1479 Data 18 iunie 2024 09:55:09
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <fstream>

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

const int NMAX = 100001;

int T[NMAX + 1], H[NMAX + 1];

int Find(int i)
{
    if(T[i] == 0)
        return i;
    return T[i] = Find(T[i]);
}

inline void Union(int x, int y)
{
    if(H[x] < H[y])
        T[x] = y;
    else
    {
        T[y] = x;
        if(H[x] == H[y])
            H[x]++;
    }
}

int main()
{
    int n, m, op, x, y, cx, cy;
    fin >> n >> m;
    while(m--)
    {
        fin >> op >> x >> y;
        cx = Find(x);
        cy = Find(y);
        if(op == 1)
        {
            if(cx != cy)
                Union(cx, cy);
        }
        else
        {
            if(cx == cy)
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
    return 0;
}