Nu aveti permisiuni pentru a descarca fisierul tree.jpg

Cod sursa(job #3001613)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 13 martie 2023 19:57:08
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
using namespace std;

ifstream cin("disjoint.in");
ofstream cout("disjoint.out");

const int MAX = 1e5+1;

int n , q , op , a , b;

struct DSU{

    int t[MAX] , h[MAX];

    void init(){

        for(int i = 1 ; i <= n ; i++){

            h[i] = t[i] = 0;
        }
    }

    int findc( int x ){

        int r = x , aux;

        while(t[x]){

            x = t[x];
        }

        swap(x,r);

        while(t[x]){

            aux = t[x];

            t[x] = r;

            x = aux;
        }

        return r;
    }

    void unionp( int x , int y ){

        x = findc(x);
        y = findc(y);

        if(x==y) return;

        if(h[x] == h[y]){

            h[y]++;

            t[x] = y;

        }else{

            if(h[x] > h[y]) swap(x,y);

            t[x] = y;
        }
    }

    void verif(int a , int b){

        a = findc(a);
        b = findc(b);

        if(a == b) cout << "DA";
        else cout << "NU";

        cout << '\n';

    }

}uf;

int main(){

    cin >> n >> q;

    uf.init();

    while(q--){

        cin >> op >> a >> b;

        if(op == 1) uf.unionp(a,b);
        else uf.verif(a,b);
    }

    return 0;
}