Cod sursa(job #2746618)

Utilizator HerddexJinga Tudor Herddex Data 28 aprilie 2021 09:16:04
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>
using namespace std;

struct DisjointSetNode {
    int parent;
    int rank;
};

int representative_of(int x, DisjointSetNode* disjoint_set) {
    vector<int> nodes;
    while(disjoint_set[x].parent != x) {
        nodes.push_back(x);
        x = disjoint_set[x].parent;
    }
    for(const auto &t : nodes)
        disjoint_set[t].parent = x;
    return x;
}

int main() {
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    DisjointSetNode disjoint_set[100001];
    int N, M;
    fin >> N >> M;
    for (int i = 1; i <= N; i++) {
        disjoint_set[i].parent = i;
        disjoint_set[i].rank = 1;
    }

    while(M--) {
        int cod, x, y;
        fin >> cod >> x >> y;
        if(cod == 1) {
            int rep_x = representative_of(x, disjoint_set);
            int rep_y = representative_of(y, disjoint_set);
            if(disjoint_set[rep_x].rank > disjoint_set[rep_y].rank) {
                disjoint_set[rep_y].parent = rep_x;
            }
            else if(disjoint_set[rep_x].rank < disjoint_set[rep_y].rank) {
                disjoint_set[rep_x].parent = rep_y;
            }
            else {
                disjoint_set[rep_x].parent = rep_y;
                disjoint_set[rep_y].rank++;
            }
        }
        else
            fout << (representative_of(x, disjoint_set) == representative_of(y, disjoint_set) ? "DA" : "NU") << '\n';
    }

    fin.close();
    fout.close();
    return 0;
}