Cod sursa(job #2009798)

Utilizator Stefan_RaduStefan Radu Stefan_Radu Data 10 august 2017 21:29:21
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
 
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
 
class Graph {
public:
 
  Graph(int n) {
    this -> n = n;
    _root.resize(n + 1);
    _size.resize(n + 1);
    for (int i = 1; i <= n; i ++) {
      _size[i] = 1;
      _root[i] = i;
    }
  }
 
  void link(int x, int y) {
    _link(x, y);
  }
 
  void query(int x, int y) {
    _get_root(x) == _get_root(y) ? cout << "DA" << '\n' : cout << "NU" << '\n';
  }
private:
 
  int n;
  vector < int > _size;
  vector < int > _root;

  int _get_root(int node) {
    int r = node;
    while (r != _root[r])
      r = _root[r];

    while (node != _root[node]) {
      int aux = _root[node];
      _root[node] = r;
      node = aux;
    }
    return _root[node];
  }
 
  void _link(int x, int y) {
    x = _get_root(x);
    y = _get_root(y);

    if (_size[x] >= _size[y]) {
      _size[x] += _size[y];
      _root[y] = _root[x]; 
    }
    else {
      _size[y] += _size[x];
      _root[x] = _root[y];
    }
  }
};
 
int main() {
  int n, m;
  cin >> n >> m;
 
  Graph *graph = new Graph(n);
 
  for (int i = 1; i <= m; i ++) {
    int type;
    cin >> type;
    if (type == 1) {
      int x, y;
      cin >> x >> y;
      graph -> link(x, y);
    }
    else {
      int x, y;
      cin >> x >> y;
      graph -> query(x, y);
    }
  }
}