Cod sursa(job #3190658)

Utilizator divadddDavid Curca divaddd Data 7 ianuarie 2024 19:58:43
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
using namespace std;
int n,q;

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

struct DSU {
    int n;
    vector<int> t, sz;
    DSU(int _n){
        n = _n;
        t.resize(n+1);
        sz.resize(n+1);
        for(int i = 1; i <= n; i++){
            t[i] = i;
            sz[i] = 1;
        }
    }
    int root(int nod){
        if(t[nod] == nod){
            return nod;
        }
        return t[nod] = root(t[nod]);
    }
    void join(int x, int y){
        x = root(x);
        y = root(y);
        if(sz[x] < sz[y]){
            swap(x, y);
        }
        t[y] = x;
        sz[x] += sz[y];
    }
    bool areJoined(int x, int y){
        return (root(x) == root(y));
    }
};

int main()
{
    fin >> n >> q;
    DSU ds(n);
    while(q--){
        int t,x,y;
        fin >> t >> x >> y;
        if(t == 1){
            ds.join(x, y);
        }else{
            fout << (ds.areJoined(x, y) ? "DA" : "NU") << "\n";
        }
    }
    return 0;
}