Cod sursa(job #2794249)

Utilizator TeodorLuchianovTeo Luchianov TeodorLuchianov Data 4 noiembrie 2021 15:52:53
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream in("disjoint.in");
ofstream out("disjoint.out");

int const NMAX = 100000;
int root[1 + NMAX];
int sizetree[1 + NMAX];

int computeRoot(int node) {
  if(root[node] == node){
    return node;
  }else {
    root[node] = computeRoot(root[node]);
    return root[node];
  }
}

void connectNodes(int a, int b) {
  int rootA = computeRoot(a), rootB = computeRoot(b);
  if(sizetree[rootA] < sizetree[rootB]){
    root[rootA] = rootB;
  }else {
    root[rootB] = rootA;
  }
}

bool areConnected(int a, int b) {
  int rootA = computeRoot(a), rootB = computeRoot(b);
  return (rootA == rootB);
}

int main() {

  int n, m;
  in >> n >> m;
  for(int i = 1;i <= n;i++){
    root[i] = i;
  }
  for(int i = 1;i <= m;i++){
    int cer, a, b;
    in >> cer >> a >> b;
    if(cer == 1){
      connectNodes(a, b);
    }else {
      if(areConnected(a, b)){
        out << "DA\n";
      }else {
        out << "NU\n";
      }
    }
  }
  return 0;
}