Cod sursa(job #3252806)

Utilizator andrei.nNemtisor Andrei andrei.n Data 31 octombrie 2024 11:28:43
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;

class DSU
{
public:
    void build(int n)
    {
        for(int i=1; i<=n; ++i)
        {
            root[i] = i;
            s[i] = 1;
        }
    }

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

    int getRoot(int x)
    {
        int cx = x;
        while(x != root[x]) x = root[x];
        while(cx != root[cx])
        {
            cx = root[cx];
            root[cx] = x;
        }
        return x;
    }

    bool query(int a, int b)
    {
        return getRoot(a) == getRoot(b);
    }

    void update(int a, int b)
    {
        if(query(a,b)) return;
//        if(s[getRoot(a)] > s[getRoot(b)]) swap(a,b);
        root[getRoot(a)] = getRoot(b);
        s[getRoot(b)] += s[getRoot(a)];
        s[getRoot(a)] = 0;
    }

private:
    int root[100005],s[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;
}