Cod sursa(job #3175676)

Utilizator DenisONIcBanu Denis Andrei DenisONIc Data 26 noiembrie 2023 12:16:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.1 kb
#include <bits/stdc++.h>
using namespace std;
void debug_out() { cerr << endl; }
template<class T> ostream& prnt(ostream& out, T v) { out << v.size() << '\n'; for(auto e : v) out << e << ' '; return out;}
template<class T> ostream& operator<<(ostream& out, vector <T> v) { return prnt(out, v); }
template<class T> ostream& operator<<(ostream& out, set <T> v) { return prnt(out, v); }
template<class T1, class T2> ostream& operator<<(ostream& out, map <T1, T2> v) { return prnt(out, v); }
template<class T1, class T2> ostream& operator<<(ostream& out, pair<T1, T2> p) { return out << '(' << p.first << ' ' << p.second << ')'; }
template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << H; debug_out(T...);}
#define dbg(...) cerr << #__VA_ARGS__ << " ->", debug_out(__VA_ARGS__)
#define dbg_v(x, n) do{cerr<<#x"[]: ";for(int _=0;_<n;++_)cerr<<x[_]<<" ";cerr<<'\n';}while(0)
#define dbg_ok cerr<<"OK!\n"
#define ll long long
#define ld long double
#define ull unsigned long long
#define pii pair<int,int>
#define MOD 1000000007
#define zeros(x) x&(x-1)^x
#define fi first
#define se second
#define NMAX 100005
const long double PI = acos(-1);

int t[NMAX], h[NMAX];
int n, m, o, x, y;

int rad(int x) {
  while (t[x] != x) {
    x = t[x];
  }
  return x;
}

void _union(int x, int y) {
  int rx = rad(x);
  int ry = rad(y);
  
  if (rx == ry) return;

  if (h[rx] > h[ry]) swap(rx, ry);

  t[rx] = ry;

  if (h[rx] == h[ry]) {
    h[ry]++;
  }
}

bool _find(int x, int y) {
  int rx = rad(x);
  int ry = rad(y);

  while (t[x] != x) {
    int p = t[x];
    t[x] = rx;
    x = p;
  }

  while (t[y] != y) {
    int p = t[y];
    t[y] = ry;
    y = p;
  }

  return rx == ry;
}

int main(){
  ios::sync_with_stdio(false);
  
  freopen("disjoint.in", "r", stdin);
  freopen("disjoint.out", "w", stdout);

  scanf("%d%d", &n, &m);

  for (int i=1;i<=n;i++) {
    t[i] = i;
    h[i] = 1;
  }

  for (int i=1;i<=m;i++) {
    scanf("%d%d%d", &o, &x, &y);
    if (o==1) {
      _union(x, y);
    } else {
      if (_find(x, y)) {
        cout << "DA\n";
      } else {
        cout << "NU\n";
      }
    }
  }

  return 0;
}