Cod sursa(job #3190047)

Utilizator divadddDavid Curca divaddd Data 6 ianuarie 2024 20:52:29
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#define MAX 100002
using namespace std;
int n,m,tip,x,y,t[MAX];
/// t[x] = -k, nr de noduri al arborelui cu radacina x
///         j, unde j este tatal lui x

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

int get_root(int x){
    int aux = x;
    while(t[x] > 0){
        x = t[x];
    }
    int root = x;
    x = aux;
    /// comprimam drumul
    while(x != root){
        aux = t[x];
        t[x] = root;
        x = aux;
    }
    return root;
}

void join(int x, int y){
    int root_x = get_root(x);
    int root_y = get_root(y);
    if(root_x == root_y){
        /// sunt deja in aceasi multime
        return;
    }
    if(t[root_x] <= t[root_y]){
        /// x are mai multe noduri decat y   | => punem arborele y in x
        /// pentru ca numerele sunt negative |    (cel mic in cel mare)
        t[root_x] += t[root_y]; /// schimbam nr de noduri
        t[root_y] = root_x;
    }else{
        /// y are mai multe noduri decat x => punem x in y
        t[root_y] += t[root_x];
        t[root_x] = root_y;
    }
}

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

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