Cod sursa(job #2810366)

Utilizator DayanamdrMardari Dayana Raluca Dayanamdr Data 29 noiembrie 2021 12:15:25
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

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

const int max_nr_nodes = 100001;

struct Node {
    int parent;
    int node_rank;
};

vector <Node> parent_vector(max_nr_nodes);

int find_root_node(int current_node) {
    if (parent_vector[current_node].parent == -1) {
        return current_node;
    }
    return parent_vector[current_node].parent = find_root_node(parent_vector[current_node].parent);
}

void make_sets_union(int x, int y) {
    int x_root_parent = find_root_node(x);
    int y_root_parent = find_root_node(y);
    if (parent_vector[x_root_parent].node_rank > parent_vector[y_root_parent].node_rank) {
        parent_vector[y_root_parent].parent = x;
    } else if (parent_vector[x_root_parent].node_rank < parent_vector[y_root_parent].node_rank) {
        parent_vector[x_root_parent].parent = y;
    } else {
        parent_vector[y_root_parent].parent = x;
        ++parent_vector[x_root_parent].node_rank;
    }
}

bool check_sets(int x, int y) {
    int x_root_parent = find_root_node(x);
    int y_root_parent = find_root_node(y);
    return x_root_parent == y_root_parent;
}
int main() {
    int n, m;
    f >> n >> m;
    for (int i = 1; i <= n; ++i) {
        parent_vector[i].parent = -1;
        parent_vector[i].node_rank = 0;
    }
    for (int i = 1; i <= m; ++i) {
        int operation, x, y;
        f >> operation >> x >> y;
        if (operation == 1) {
            make_sets_union(x, y);
        } else {
            int are_in_the_same_set = check_sets(x, y);
            if (are_in_the_same_set) {
                g << "DA\n";
            } else {
                g << "NU\n";
            }
        }
    }
    return 0;
}