Cod sursa(job #2685620)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 17 decembrie 2020 13:29:38
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 kb
#include <iostream>
#include <fstream>

const int NMAX = 1e5;

int n, m;

int t[1 + NMAX];

int h[1 + NMAX];

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

  t[x] = root(t[x]);
  return t[x];
}

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

  if (h[x] < h[y])
    t[x] = y;
  else if (h[x] > h[y])
    t[y] = x;
  else {
    t[x] = y;
    ++h[y];
  }
}

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

int main() {
  std::ifstream in("disjoint.in");
  std::ofstream out("disjoint.out");

  in >> n >> m;

  for (int i = 1; i <= n; ++i) {
    t[i] = i;
    h[i] = 1;
  }

  int op, x, y;
  for (int i = 1; i <= m; ++i) {
    in >> op >> x >> y;
    if (op == 1)
      union_(x, y);
    else
    out << (find_(x, y) ? "DA" : "NU") << '\n';
  }

  return 0;
}