Cod sursa(job #3150286)

Utilizator andiRTanasescu Andrei-Rares andiR Data 15 septembrie 2023 23:12:22
Problema Paduri de multimi disjuncte Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <deque>
#include <iomanip>
#include <vector>

#pragma GCC optimize("O3")
#define fi first
#define se second
#define pb push_back
#define pf push_front

using namespace std;
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
typedef long long ll;
const ll Nmax=1e6+5, inf=1e9+5;
using pll=pair<ll, ll>;
struct DSU{
    vector <int> rep, s;
    DSU (int n){
        rep.resize(n);
        s.resize(n);
        for (int i=0; i<n; i++){
            rep[i]=i;
            s[i]=1;
        }
    }
    int get_rep (int n){
        if (n==rep[n])
            return n;
        return rep[n]=get_rep(rep[n]); //path compression
    }
    int get_size(int n){
        return s[get_rep(n)];
    }
    bool same_set(int a, int b){
        return get_rep(a)==get_rep(b);
    }
    void join (int a, int b){
        int ra=get_rep(a),
            rb=get_rep(b);
        if (ra==rb)
            return;
        if (s[ra]>s[rb]){
            s[ra]+=s[rb];
            rep[b]=ra;
        }
        else{
            s[rb]+=s[ra];
            rep[a]=rb;
        }
    }
};

int n, m, t, a, b;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    fin>>n>>m;
    DSU dsu(n);
    for (int i=0; i<m; i++){
        fin>>t>>a>>b;
        a--; b--;
        if (t==1)
            dsu.join(a, b);
        else if (dsu.same_set(a, b))
            fout<<"DA\n";
        else fout<<"NU\n";
    }
    return 0;
}