Cod sursa(job #2839201)

Utilizator Ciprian089Cirstea Ciprian Ciprian089 Data 25 ianuarie 2022 15:14:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include<fstream>

using namespace std;

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

int n , m , cod , x,  y , t[100001];

int get_root(int node){
    while(t[node] > 0)
        node = t[node];
    return node;
}

void join(int x , int y){
    int root_x = get_root(x);
    int root_y = get_root(y);
    
    if(root_x == root_y){
        return;
    }
        
    else if(t[root_x] <= t[root_y]){
        t[root_x] += t[root_y];
        t[root_y] = root_x;
    }
    else{
        t[root_y] += t[root_x];
        t[root_x] = root_y;
    }
}

bool querry(int x, int y){
    return get_root(x) == get_root(y);
}


int main(){
        
    fin >> n >> m;
    for(int i = 1; i <= m; i++){
        fin >> cod >> x >> y;
        if(cod == 1){
            join(x ,y);
        }
        else if(cod == 2){
            if(querry(x , y))       
                fout << "DA" << "\n";
            else
                fout << "NU" << "\n";
        }
    }
    
    return 0;
}