Cod sursa(job #2936519)

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

vector <pair <int, int>> t;

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

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

bool joinDSU(int x, int y){
  x = getRoot(x);
  y = getRoot(y);
  if (t[x].second < t[y].second)
    swap(x, y);
  if (x == y)
    return false;
  t[y].first = x;
  t[x].second += t[y].second;
  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;
}