Cod sursa(job #2876808)

Utilizator PopaMihaimihai popa PopaMihai Data 23 martie 2022 17:18:48
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 1e5 + 3;

int N, Q;

static inline void myswap(int &a, int &b)
{
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
}

class DSU
{
    int sef[NMAX];
    vector < int > List[NMAX];

public:

    inline void Init(int n)
    {
        for(int i = 1; i <= n; ++i)
            List[i].push_back(i), sef[i] = i;
        return;
    }

    inline bool Query(int x, int y)
    {
        return (sef[x] == sef[y]);
    }

    inline void Update(int x, int y)
    {
        x = sef[x];
        y = sef[y];

        if(List[x].size() > List[y].size())
            myswap(x, y);

        if(x == y)
            return;

        sef[x] = y;
        for(auto it: List[x]) {
            sef[it] = y;
            List[y].push_back(it);
        }
        List[x].clear();

        return;
    }
}dsu;

static inline void Solve()
{
    fin >> N >> Q;
    dsu.Init(N);
    int tip, x, y;
    for(int i = 1; i <= Q; ++i) {
        fin >> tip >> x >> y;
        if(tip == 1)
            dsu.Update(x, y);
        else fout << (dsu.Query(x, y) ? "DA\n" : "NU\n");
    }

    return;
}

int main()
{
    Solve();
    return 0;
}