Cod sursa(job #2951194)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 5 decembrie 2022 17:44:25
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>

using namespace std;

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

const int MAX = 1e5+1;

int n , m , a , b , c;

struct unionfind{

    int t[MAX] , h[MAX];

    void init(){

        for(int i = 1 ; i <= n ; i++){
            t[i] = h[i] = 0;
        }
    }

    int findc( int x ){

        int r = x , aux;

        while(t[r]) r = t[r];

        while(t[x]){

            aux = t[x];
            t[x] = r;
            x = aux;
        }

        return r;
    }

    void unionp( int x, int y ){

        int a = findc(x);
        int b = findc(y);

        if( a == b ){

            return;
        }

        if( h[a] < h[b] ){

            swap(a,b);
        }

        t[b] = a;

        if( h[a] == h[b] ) h[a]++;

    }

} x ;

int main()
{

    cin >> n >> m;

    x.init();

    while(m--){

        cin >> a >> b >> c;

        if( a == 1 ) x.unionp(b,c);
        else{

            if( x.findc(b) == x.findc(c) ) cout << "DA";
            else cout << "NU";
            cout << '\n';
        }
    }

    return 0;
}