Cod sursa(job #2846378)

Utilizator iraresmihaiiordache rares mihai iraresmihai Data 9 februarie 2022 10:23:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <iostream>

using namespace std;

#define MAXN 100000
#define UNION 1

struct number{
  int father;
};

number v[MAXN + 1];

int findFather(int x) {
  if ( v[x].father == 0 )
    return x;
  return v[x].father = findFather(v[x].father);
}

void unite(int x, int y) {
  int fatherX, fatherY;

  fatherX = findFather(x);
  fatherY = findFather(y);

  if ( fatherX != fatherY ) {
    v[fatherY].father = fatherX;
  }
}

int main() {
  FILE *fin, *fout;
  fin = fopen("disjoint.in", "r");
  fout = fopen("disjoint.out", "w");

  int n, q, c, x, y;

  fscanf(fin, "%d%d", &n, &q);

  while ( q-- ) {
    fscanf(fin, "%d%d%d", &c, &x, &y);

    if ( c == UNION ) {
      unite(x, y);
    } else {
      if ( findFather(x) == findFather(y) )
        fprintf(fout, "DA\n");
      else
        fprintf(fout, "NU\n");
    }
  }

  fclose(fin);
  fclose(fout);
  return 0;
}