Cod sursa(job #2936510)

Utilizator AlexandruBenescuAlexandru Benescu AlexandruBenescu Data 8 noiembrie 2022 21:58:40
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

vector <int> t;

void initDSU(int n){
  t.resize(n + 1);
  for (int i = 1; i <= n; i++)
    t[i] = i;
}

int getRoot(int x){
  if (t[x] == x)
    return x;
  t[x] = getRoot(t[x]);
  return t[x];
}

bool joinDSU(int x, int y){
  x = getRoot(x);
  y = getRoot(y);
  if (x == y)
    return false;
  t[y] = x;
  return true;
}

int main(){
  int n, q;
  fin >> n >> q;
  initDSU(n);
  for (int i = 1; i <= q; i++){
    int type, a, b;
    fin >> type >> a >> b;
    if (type == 1)
      joinDSU(a, b);
    else
      fout << (getRoot(a) == getRoot(b) ? "DA\n" : "NU\n");
  }
  return 0;
}