Cod sursa(job #3371159)

Utilizator nstefanNeagu Stefan nstefan Data 28 octombrie 2026 19:52:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <bits/stdc++.h>
#include <cstdio>
#include <functional>
#include <utility>
using namespace std;

struct ScopeExit {
  std::function<void()> f;
  ScopeExit(std::function<void()> f) : f(std::move(f)) {}
  ~ScopeExit() {
    if (f)
      f();
  }
};

#define STRING_JOIN2(arg1, arg2) DO_STRING_JOIN2(arg1, arg2)
#define DO_STRING_JOIN2(arg1, arg2) arg1##arg2

#define SCOPE_EXIT(code)                                                       \
  ScopeExit STRING_JOIN2(scope_exit_, __LINE__)([=]() { code; })

///////////

#ifdef INFOARENA
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
#define cin fin
#define cout fout
#endif

///////////

struct DSU {
  vector<int> daddy;
  vector<int> size;

  DSU(int numNodes) : size(numNodes + 1), daddy(numNodes + 1) {
    fill(size.begin(), size.end(), 1);
    iota(daddy.begin(), daddy.end(), 0);
  }

  int find(int node) {
    if (daddy[node] == node)
      return node;

    return daddy[node] = find(daddy[node]);
  }

  bool merge(int x, int y) {
    int comp_x = find(x);
    int comp_y = find(y);

    if (comp_x == comp_y)
      return false;

    if (size[comp_x] > size[comp_y])
      swap(comp_x, comp_y);

    size[comp_y] += size[comp_x];
    daddy[comp_x] = comp_y;
    return true;
  }
};

int main() {
  int n, nops;
  cin >> n >> nops;

  DSU dsu(n);

  for (int _ = 0; _ < nops; _++) {
    int op, x, y;
    cin >> op >> x >> y;

    if (op == 1) {
      dsu.merge(x, y);
    } else {
      cout << (dsu.find(x) == dsu.find(y) ? "DA" : "NU") << '\n';
    }

    // printf("[DEBUG]\n");
    // for (int i = 0; i < dsu.daddy.size(); i++)
    //   printf("daddy[%d]: %d\n", i, dsu.daddy[i]);
    // printf("\n");
  }
}