Cod sursa(job #2238930)

Utilizator NewGloryMihnea Andreescu NewGlory Data 8 septembrie 2018 14:04:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <iostream>
#include <cstdio>

using namespace std;

const int N = 100000 + 5;

int n, q;

int t[N], h[N];

inline int dad(int nod) {
  if (t[nod] == nod) {
    return nod;
  }
  t[nod] = dad(t[nod]);
  return t[nod];
}

inline int unite(int a, int b) {
  a = dad(a);
  b = dad(b);
  if (h[a] > h[b]) {
    t[b] = a;
  }
  else {
    t[a] = b;
    if (h[a] == h[b]) {
      h[a] ++;
    }
  }
}


int main () {
  freopen("disjoint.in", "r", stdin);
  freopen("disjoint.out", "w", stdout);
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin>>n>>q;
  for (int i = 1; i <= n; i++) {
    t[i] = i;
    h[i] = 1;
  }
  while (q--) {
    int type;
    cin>>type;
    if (type == 1) {
      int a, b;
      cin>>a>>b;
      unite(a, b);
    }
    else {
      int a, b;
      cin>>a>>b;
      if (dad(a) == dad(b)) {
        cout<<"DA\n";
      }
      else {
        cout<<"NU\n";
      }
    }
  }
  return 0;
}