Cod sursa(job #3372336)

Utilizator RaducuSebasRaducu Sebastian RaducuSebas Data 3 noiembrie 2026 11:30:19
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <fstream>
#include <stdio.h>
#define NMAX 100020
int TT[NMAX], RG[NMAX];
int N, M;

int find(int x) {
  int R, y;
  R = x;
  while (TT[R] != R)
    R = TT[R];

  while (TT[x] != x) {
    y = TT[x];
    TT[x] = R;
    x = y;
  }
  return R;
}

void unite(int x, int y) {
  if (RG[x] > RG[y])
    TT[y] = x;
  else
    TT[x] = y;

  if (RG[x] == RG[y])
    RG[y]++;
}
using namespace std;
int main() {

  ifstream fin("disjoint.in");
  ofstream fout("disjoint.out");
  fin >> N >> M;
  int i, x, y, cd;

  for (i = 1; i <= N; i++) {
    TT[i] = i;
    RG[i] = 1;
  }

  for (i = 1; i <= M; i++) {
    fin >> cd >> x >> y;
    if (cd == 2) {
      if (find(x) == find(y))
        fout << "DA\n";
      else
        fout << "NU\n";
    } else
      unite(find(x), find(y));
  }

  return 0;
}