Cod sursa(job #3267030)

Utilizator divadddDavid Curca divaddd Data 11 ianuarie 2025 01:22:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>
using namespace std;
int n,q;

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

struct DSU {
  int n;
  vector<int> t, sz;
  DSU(){}
  DSU(int _n){
    n = _n;
    sz.resize(n+1, 1);
    t.resize(n+1);
    for(int i = 1; i <= n; i++){
      t[i] = i;
    }
  }
  int get_root(int nod){
    if(t[nod] == nod){
      return nod;
    }
    return t[nod] = get_root(t[nod]);
  }
  bool areJoined(int x, int y){
    return get_root(x) == get_root(y);
  }
  void join(int x, int y){
    if(areJoined(x, y)){
      return ;
    }
    x = get_root(x);
    y = get_root(y);
    if(sz[x] < sz[y]){
      swap(x, y);
    }
    t[y] = x;
    sz[x] += sz[y];
  }
};

int main() {
  fin >> n >> q;
  DSU dsu(n);
  for(int i = 1; i <= q; i++){
    int t, x, y;
    fin >> t >> x >> y;
    if(t == 1){
      dsu.join(x, y);
    }else{
      fout << (dsu.areJoined(x, y) ? "DA" : "NU") << "\n";
    }
  }
  return 0;
}