Cod sursa(job #3152136)

Utilizator not_anduAndu Scheusan not_andu Data 24 septembrie 2023 08:30:52
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
/**
 * Author: Andu Scheusan (not_andu)
 * Created: 23.09.2023 10:12:18
*/

#include <bits/stdc++.h>
#include <unordered_map>
#pragma GCC optimize("O3")

using namespace std;

#define INFILE "disjoint.in"
#define OUTFILE "disjoint.out"

#define all(x) (x).begin(), (x).end()

typedef long long ll;

class DSU {

    private:

        vector<int> parent;
        vector<int> size;

    public:

        DSU() {
            // nothing in here
        }

        DSU(int n){

            parent.resize(n + 1);
            size.resize(n + 1, 1);

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

                parent[i] = i;

            }

        }

        int findParent(int val){

            if(parent[val] == val){
                return val;
            }

            return findParent(parent[val]);

        }

        void unionSets(int m, int n){

            int repM = findParent(m);
            int repN = findParent(n);

            if(repM != repN){

                if(size[repM] > size[repN]){

                    parent[repN] = repM;
                    size[repM] += size[repN];

                }
                else{

                    parent[repM] = repN;
                    size[repN] += size[repM];

                }

            }

        }
};

void solve(){

    int n, m;
    vector<int> v;

    cin >> n >> m;

    DSU dsu(n);

    for(int i = 0; i < m; ++i){

        short tip;
        int x, y;

        cin >> tip >> x >> y;

        if(tip == 1){

            dsu.unionSets(x, y);

        }
        else{

            if(dsu.findParent(x) == dsu.findParent(y)){

                cout << "DA" << '\n';

            }
            else{

                cout << "NU" << '\n';

            }

        }

    }

}

int main(){
    
    ios_base::sync_with_stdio(false);

    freopen(INFILE, "r", stdin);
    freopen(OUTFILE, "w", stdout);

    cin.tie(nullptr);
    cout.tie(nullptr);

    solve();

    return 0;
}