Cod sursa(job #2938255)

Utilizator popashtefan10Popa Stefan popashtefan10 Data 11 noiembrie 2022 21:21:27
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <iostream>
#include <cstdio>
#define NMAX 100000

using namespace std;

int n, m;
int repr[NMAX + 5];

int get_repr(int x) {
  while(x != repr[x])
    x = repr[x];
  return x;
}

void set_repr(int x, int rx) {
  int aux;

  while(x != repr[x]) {
    aux = x;
    x = repr[x];
    repr[aux] = rx;
  }
  repr[x] = rx;
}

int main() {
  freopen("disjoint.in", "r", stdin);
  freopen("disjoint.out", "w", stdout);
  int cod, x, y;

  scanf("%d %d", &n, &m);
  for(int i = 1; i <= n; ++i)
    repr[i] = i;

  for(int i = 1; i <= m; ++i) {
    scanf("%d %d %d", &cod, &x, &y);
    int rx = get_repr(x), ry = get_repr(y);
    if(cod == 1) {
      if(rx != ry)
        set_repr(x, ry);
    }
    else {
      if(rx == ry)
        printf("DA\n");
      else
        printf("NU\n");
      repr[x] = rx;
      repr[y] = ry;
    }
  }

  return 0;
}