Cod sursa(job #3252772)

Utilizator andrei.nNemtisor Andrei andrei.n Data 30 octombrie 2024 23:26:06
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>

using namespace std;

class DSU
{
public:
    void build(int n)
    {
        for(int i=1; i<=n; ++i)
        {
            comp[i] = i;
            mult[i].emplace_back(i);
        }
    }

    DSU() = default;
    DSU(int n) {build(n);}

    bool query(int a, int b)
    {
        return comp[a] == comp[b];
    }

    void update(int a, int b)
    {
        if(query(a,b)) return;
        if(mult[comp[a]].size() > mult[comp[b]].size()) swap(a,b);
        int ca = comp[a], cb = comp[b];
        for(auto &i:mult[ca])
        {
            comp[i] = cb;
            mult[cb].emplace_back(i);
        }
        mult[ca].clear();
    }

private:
    int comp[100005];
    vector<int> mult[100005];
};

DSU dsu;

int main()
{
    ifstream fin ("disjoint.in");
    ofstream fout ("disjoint.out");
    ios::sync_with_stdio(false); fin.tie(0); fout.tie(0);
    int n,m;
    fin>>n>>m;
    dsu.build(n);
    while(m--)
    {
        int t,x,y; fin>>t>>x>>y;
        if(t == 1) dsu.update(x,y);
        else fout<<(dsu.query(x,y) ? "DA" : "NU")<<'\n';
    }
    return 0;
}