Cod sursa(job #2686421)

Utilizator AntoniuFicAntoniu Ficard AntoniuFic Data 19 decembrie 2020 09:54:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <vector>
#include <fstream>

using namespace std;

struct node{
    int value, depth;
    node *parent;

    node(int v, int d, node *p = nullptr){
        this->value = v;
        this->depth = d;
        this->parent = p;
    }
    node* root(){
        if(this->parent == nullptr) return this;
        this->parent = this->parent->root();
        return this->parent;
    }

};

void query(node* x, node* y, ofstream &g){
    if(x->root() == y->root()) g<<"DA"<<"\n";
    else g<<"NU"<<"\n";
}

void update(node* x, node* y){
    if(x->depth < y->depth) x->root()->parent = y;
    else if(x->depth > y->depth) y->root()->parent = x;
    else{
        x->depth++, y->depth++;
        x->root()->parent = y;
    }
}

int main() {
    int n, m;
    ifstream f("disjoint.in");
    ofstream g("disjoint.out");
    f>>n>>m;
    vector<node*> nodes;
    nodes.reserve(n);
    for (int i = 0; i < n; ++i) {
        nodes.push_back(new node(i, 1, nullptr));
    }
    for (int i = 0; i < m; ++i) {
        int x, y, o;
        f>>o>>x>>y;
        if(o == 1) update(nodes[x - 1], nodes[y - 1]);
        else query(nodes[x - 1], nodes[y - 1], g);
    }
    return 0;
}