Cod sursa(job #3318906)

Utilizator Darius_PurcaruPurcaru Darius Constantin Darius_Purcaru Data 29 octombrie 2025 17:25:23
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>

using namespace std;

int tata[100005];
vector<int> nr(100005, 1);

int Find(int x) {
  if (tata[x] == 0) {
    return x;
  }
  else if (tata[tata[x]] == 0) {
    return tata[x];
  }
  return tata[x] = Find(tata[x]);
}

void Union(int x, int y) {
  if (Find(x) == Find(y)) {
    return;
  }
  if (nr[x] < nr[y]) {
    tata[Find(x)] = Find(y);
    nr[y] += nr[x];
  }
  else {
    tata[Find(y)] = Find(x);
    nr[y] += nr[x];
  }
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  freopen("disjoint.in", "r", stdin);
  freopen("disjoint.out", "w", stdout);
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; ++i) {
    int cod, x, y;
    cin >> cod >> x >> y;
    switch (cod) {
      case 1:
        Union(x, y);
        break;
      default:
        switch (Find(x) == Find(y)) {
          case true:
            cout << "DA\n";
            break;
          default:
            cout << "NU\n";
            break;
        }
        break;
    }
  }
  return 0;
}