Cod sursa(job #2009657)

Utilizator Stefan_RaduStefan Radu Stefan_Radu Data 10 august 2017 13:34:15
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream cin("disjoint.in");
ofstream cout("disjoint.out");

class Graph {
public:

  Graph(int n) {
    this -> n = n;
    _node.resize(n + 1);
    _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) {
    _root[x] == _root[y] ? cout << "DA" << '\n' : cout << "NU" << '\n';
  }
private:

  int n;
  vector < vector < int > > _node;
  vector < int > _size;
  vector < int > _root;

  void ch_root(int r, int y) {
    _root[y] = r;
    for (int el : _node[y]) {
      if (_root[el] == r) 
        continue; 
      ch_root(r, el);
    }
  }

  void _link(int x, int y) {
    if (_size[_root[x]] >= _size[_root[y]]) {
      _node[x].push_back(_root[y]);
      ch_root(_root[x], _root[y]);
      _size[_root[x]] += _size[_root[y]];
    }
    else {
      _node[_root[y]].push_back(_root[x]);
      ch_root(_root[y], _root[x]);
      _size[_root[y]] += _size[_root[x]];
    }
  }
};

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);
    }
  }
}