Cod sursa(job #2975569)

Utilizator Vlad.Vlad Cristian Vlad. Data 6 februarie 2023 19:54:00
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <iostream>
#define NMAX 100005
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

struct node {
    node *parent;
    int rang;
};

node* v[NMAX];

node* cauta(node* a) {
    if (a->parent != nullptr) {
        a->parent = cauta(a->parent);
        return a->parent;
    }
    return a;
}

void reuneste(node* a, node* b) {
    a = cauta(a);
    b = cauta(b);
    if (a != b) {
        if (a->rang > b->rang) {
            b->parent = a;
        }
        else if  (a->rang < b->rang) {
            a->parent = b;
        }
        else {
            b->parent = a;
            a->rang += 1;
        }
    }
}

int main()
{
    int N, M;
    fin >> N >> M;
    for (int i = 1; i <= N; ++i) {
        v[i] = new node;
        v[i]->parent = nullptr;
    }
    int x, y, p;
    for (int i = 0; i < M; ++i) {
        fin >> p >> x >> y;
        if (p == 1) {
            reuneste(v[x], v[y]);
        }
        else {
            if (cauta(v[x]) == cauta(v[y])) {
                fout << "DA\n";
            }
            else {
                fout << "NU\n";
            }
        }
    }
    return 0;
}