Cod sursa(job #2456469)

Utilizator tudi98Cozma Tudor tudi98 Data 14 septembrie 2019 14:16:35
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.67 kb
#include <bits/stdc++.h>
using namespace std;

int P[100005];
int h[100005];

int root(int x) {
  if (P[x] == x) return x;
  return root(P[x]);
}

void unite(int x, int y) {
  int rx = root(x);
  int ry = root(y);
  if (h[rx] > h[ry]) {
    P[ry] = rx;
    h[rx]++;
  } else {
    P[rx] = ry;
    h[ry]++;
  }
}

int main() {
  ios_base::sync_with_stdio(false);
  ifstream cin("disjoint.in");
  ofstream cout("disjoint.out");

  int n, m;
  cin >> n >> m;

  for (int i = 1; i <= n; ++i) P[i] = i, h[i] = 1;

  while (m--) {
    int t, x, y;
    cin >> t >> x >> y;
    if (t == 1) {
      unite(x, y);
    } else {
      cout << (root(x) == root(y) ? "DA\n" : "NU\n");
    }
  }
}