Cod sursa(job #2924020)

Utilizator Alex_HossuHossu Alexandru Alex_Hossu Data 23 septembrie 2022 09:49:46
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <iostream>
#include <stdio.h>
using namespace std;

#define MAX_N 100005

struct UF_node {
  int par = -1;
  int siz = 1;
};
UF_node UF[MAX_N];

int root(int pos) {
  return (UF[pos].par == -1) ? pos : UF[pos].par = root(UF[pos].par);
}

inline bool check(int pos1, int pos2) { return root(pos1) == root(pos2); }

void unite(int pos1, int pos2) {
  pos1 = root(pos1);
  pos2 = root(pos2);
  if (UF[pos2].siz < UF[pos1].siz) {
    std::swap(pos1, pos2);
  }
  UF[pos1].par = pos2;
  UF[pos2].siz += UF[pos1].siz;
}

int main() {
  FILE *fin, *fout;
  int n, m;
  int i, op, x, y;

  fin = fopen("disjoint.in", "r");
  fout = fopen("disjoint.out", "w");

  fscanf(fin, "%d%d", &n, &m);
  for (i = 0; i < m; i++) {
    fscanf(fin, "%d%d%d", &op, &x, &y);
    if (op == 1)
      unite(x, y);
    else {
      fprintf(fout, "%s\n", check(x, y) ? "DA" : "NU");
    }
  }

  fclose(fin);
  fclose(fout);
}