Cod sursa(job #3218531)

Utilizator MirunaAfloroaieAfloroaie Pricop Miruna MirunaAfloroaie Data 27 martie 2024 12:29:39
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>
#define NMAX 100008

using namespace std;

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

int tata[NMAX];
int h[NMAX];

void Union(int x, int y){

    if (h[x] < h[y])
        tata[x] = y;
    else
        if (h[y] < h[x])
            tata[y] = x;
            else{
                tata[y] = x;
                h[x]++;
            }
}

int Find(int x){

    int r, y;
    r = x;

    while (tata[r] != 0)
        r = tata[r];

    while(tata[x] != 0){
        y = tata[x];
        tata[x] = r;
        x = y;
    }

    return r;
}

int main()
{
    int n, m, x, y, caz;
    fin >> n >> m;

    for (int i = 1; i <= m; i++){
        fin >> caz >> x >> y;

        int t1 = Find(x);
        int t2 = Find(y);

        if (caz == 1){
            if (t1 != t2)
                Union(t1, t2);
        }
        else{
            if (t1 == t2)
                fout << "DA" << '\n';
            else
                fout << "NU" << '\n';
        }
    }
    return 0;
}