Cod sursa(job #2695581)

Utilizator dianapingu1Diana Vasiliu dianapingu1 Data 13 ianuarie 2021 19:38:08
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>

using namespace std;

const int NMAX = 100001;

int n,m;
int reprez[NMAX];
int componenta[NMAX];

int find_reprez(int node) {
    if (node == reprez[node]) {
        return node;
    }
    int nreprez = find_reprez(reprez[node]);
    reprez[node] = nreprez;
    return nreprez;
}

int main() {

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

    fin >> n >> m;
    for (int i = 1; i <= n; i++) {
        reprez[i] = i;
        componenta[i] = 1;
    }

    for (int i = 1; i <= m; i++) {
        int opt, x, y;
        fin >> opt >> x >> y;
        int reprez_x = find_reprez(x);
        int reprez_y = find_reprez(y);

        if (opt == 1) {
            if (reprez_x != reprez_y) {
                if (componenta[x] > componenta[y]) {
                    reprez[y] = x;
                    componenta[x] += componenta[y];
                }
                else {
                    reprez[x] = y;
                    componenta[y] += componenta[x];
                }
            }
        }
        else {
            if (reprez_x == reprez_y) {
                fout << "DA\n";
            }
            else {
                fout << "NU\n";
            }
        }
    }


    return 0;
}