Cod sursa(job #3165437)

Utilizator PescarusTanislav Luca Andrei Pescarus Data 6 noiembrie 2023 10:52:06
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>


using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
const int nmax = 100005;
int n, m;

int father[nmax];

int gaseste_tatal(int node){
    if(father[node] < 0){
        return node;
    }
    int root  = gaseste_tatal(father[node]);
    father[node] = root;
    return root;
}
void unite(int x, int y){
    int r_x = gaseste_tatal(x);
    int r_y = gaseste_tatal(y);
    if(r_x == r_y){
        return;
    }
    if(father[r_x] < father[r_y]){
        swap(r_x, r_y);
    }
    father[r_y] += father[r_x];
    father[r_x] = r_y;
}
int main(){
    f >> n >> m;
    for(int i = 1; i <= n; i++){
        father[i] = -1;
    }
    for(int i = 1; i <= n; i++){
        int x, y, z;
        f >> z >> x >> y;
        if(z == 2){
            if(gaseste_tatal(x) == gaseste_tatal(y)){
                g << "DA" << '\n';
            }
            else{
                g << "NU" << '\n';
            }
        }
        if(z == 1){
            unite(x, y);
        }
    }
}