Cod sursa(job #3366086)

Utilizator wiki__Andrei Alecu izsak wiki__ Data 29 septembrie 2026 08:51:54
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
#define int long long
const int NMAX = 2e5;
const int Mod = 1e20;

int32_t main() {

    freopen("disjoint.in","r",stdin);
    freopen("disjoint.out","w",stdout);

    std::ios_base::sync_with_stdio(0);
    std::cin.tie(0);
    std::cout.tie(0);

    struct UnionFind {
        std::vector<int> p;
        int n;

        UnionFind(int n) {
            this->n = n;
            p.resize(n+1);
            for (int i=1; i<=n; i++) {
                p[i] = i;
            }
        }

        int find_parent(int node) {
            if (p[node] == node) return node;
            p[node] = find_parent(p[node]);
            return p[node];
        }

        void union_sets(int a,int b) {
            a = find_parent(a);
            b = find_parent(b);
            if (a != b) {
                p[a] = b;
            }
        }
    };

    int n,m; std::cin>>n>>m;

    UnionFind dsu(n);
    while (m--) {
        int t; std::cin>>t;
        if (t == 1) {
            int a,b; std::cin>>a>>b;
            dsu.union_sets(a,b);
        }
        else {
            int a,b; std::cin>>a>>b;
            if (dsu.find_parent(a) == dsu.find_parent(b)) std::cout<<"DA\n";
            else std::cout<<"NU\n";
        }
    }
}