Cod sursa(job #3004035)

Utilizator begusMihnea begus Data 16 martie 2023 09:04:16
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>
using namespace std;

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

const int NMAX = 1e5+1;

int n, q, T[NMAX];

int getRoot(int node){
    int aux = node;
    while(T[node] > 0) node = T[node];
    int root = node;
    node = aux;
    while(node!=root){
        aux = T[node];
        T[node] = root;
        node = aux;
    }
    return node;
}

void join(int x, int y){
    int root_x = getRoot(x);
    int root_y = getRoot(y);
    if(root_x == root_y) return;
    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;
    }
}

void query(int x, int y){
    if(getRoot(x) == getRoot(y)) fout << "DA\n";
    else fout << "NU\n";
}

int main(){
    fin >> n >> q;
    for(int i=1; i<=n; i++) T[i] = -1;
    while(q--){
        int t, a, b;
        fin >> t >> a >> b;
        if(t==1){
            join(a, b);
        }else{
            query(a, b);
        }
    }
}