Cod sursa(job #3157870)

Utilizator PsyDuck1914Feraru Rares-Serban PsyDuck1914 Data 17 octombrie 2023 10:10:38
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("disjoint.in");
ofstream g ("disjoint.out");

const int NMAX = 1e5;
int sef[NMAX+1], h[NMAX+1];

int gasit(int x){
    int bigboss = x;
    
    while(sef[bigboss] != bigboss){
        bigboss = sef[bigboss];
    }
    
    while(sef[x] != x){
        int cp = sef[x];
        sef[x] = bigboss;
        x = cp;
    }
    
    return bigboss;
}

void uneste(int x, int y){
    if(h[x] > h[y])
        sef[y] = x;
    else sef[x] = y;
    if(h[x] == h[y])
        h[y] ++;
}

int main()
{
    int n, q;
    f >> n >> q;
    
    for(int i=1; i<=n; i++){
        sef[i] = i;
        h[i] = 1;
    }
    
    for(int i=1; i<=q; i++){
        int t, x, y;
        f >> t >> x >> y;
        if(t == 1)
            uneste(gasit(x), gasit(y));
        else{
            if(gasit(x) ==  gasit(y))
                g << "DA" << "\n";
            else g << "NU" << "\n";
        }
    }

    return 0;
}