Cod sursa(job #3375068)

Utilizator matei__bBenchea Matei matei__b Data 10 noiembrie 2026 10:17:39
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
// https://www.infoarena.ro/problema/disjoint

#include <bits/stdc++.h>
using namespace std;

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

int n,m;
struct dsu {
    vector<int> t;
    vector<int> sz;

    dsu(int n) : t(n+8, 0), sz(n+8, 0) {
        for(int i=1; i<=n; i++) {
            t[i]=i;
            sz[i]=1;
        }
    }

    int root(int x) {
        if(x==t[x]) {
            return x;
        }
        return t[x]=root(t[x]);
    }

    void unite(int x, int y) {
        x=root(x);
        y=root(y);

        if(x==y) {
            return ;
        }

        if(sz[x]<sz[y]) {
            swap(x,y);
        }
        sz[x]+=sz[y];
        t[y]=x;
    }

    bool are_conn(int x,int y) {
        return root(x)==root(y);
    }
};

int main() {
    ios_base::sync_with_stdio(false);
    fin.tie(nullptr);
    fout.tie(nullptr);

    fin >> n >> m;
    dsu v(n);

    for(int i=1; i<=m; i++) {
        int tip,x,y;
        fin >> tip >> x >> y;

        if(tip==1) {
            v.unite(x, y);
        }
        else {
            fout << (v.are_conn(x, y) ? "DA\n" : "NU\n");
        }
    }

    return 0;
}