Cod sursa(job #2954616)

Utilizator marinee.anca17@yahoo.comChiricuta Marina Anca [email protected] Data 14 decembrie 2022 21:56:57
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <fstream>
using namespace std;

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

int N, M;
int* t;
int* h;

int Root(int nod)
{
    if(t[nod] == 0) {
        return nod;
    }
    return t[nod] = Root(t[nod]);

}

void Unire(int x, int y) {
    int t_x = Root(x);
    int t_y = Root(y);

    if(h[t_x] > h[t_y]) {
        t[t_y] = t_x;
    } else if(h[t_x] < h[t_y]) {

        t[t_x] = t_y;
    } else {
        t[t_y] = t_x;
        h[t_x]++;
    }
}
int main()
{
    f>>N>>M;

    t = new int[N+1];
    h = new int[N+1];

    for(int i = 0; i<= N; i++) {
        t[i] = 0;
        h[i] = 1;
    }

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

    return 0;
}