Cod sursa(job #2804123)

Utilizator Andreea__Zavoiu Andreea Andreea__ Data 20 noiembrie 2021 23:21:02
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <vector>
#define Nmax 100001
using namespace std;

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

vector< pair<int, pair<int,int>> > cod_muchie; // m.first == codul, m.second.first = x, m.second.second = y;
int n, m, cod, tata[Nmax], rang[Nmax];

int find (int x)
{
    while (x!=tata[x])
        return find(tata[x]);
}

void uneste(int x, int y) // reuniune dupa rang <=> atasez arborelui mai mare pe cel mai mic
{
    x = find(x);
    y = find(y);

    if (rang[x] >= rang[y]) {
        tata[y] = x;
        rang[x] += rang[y];
    }
    else {
        tata[x] = y;
        rang[y] += rang[x];
    }
}

void init() {
    for (int i=0; i<n; i++) {
        tata[i] = i; // parintele
        rang[i] = 1; // dimensiunea arborelui => initial fiecare nod reprez un arbore form doar din rad
    }
}

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

//    for (int i=1; i<=m; i++) {
//        fin >> cod >> x >> y;
//        cod_muchie.push_back(make_pair(cod, make_pair(x,y)));
//    }

    init();

    // for (auto muchie : cod_muchie) {
    for (int i=1; i<=m; i++) {
        fin >> cod >> x >> y;
        //x = muchie.second.first;
        //y = muchie.second.second;

        if (cod == 1)
            uneste(x,y);
        else {
            if (find(x) == find(y)) fout << "DA\n";
            else fout << "NU\n";
        }
    }

    return 0;
}