Cod sursa(job #2009919)

Utilizator Stefan_RaduStefan Radu Stefan_Radu Data 11 august 2017 11:45:05
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 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 root, int node) {
    _root[node] = root;
    for (auto x : _node[node]) {
      if (_root[x] == root)
        continue;
      _ch_root(root, x);
    }
  }

  void _link(int x, int y) {
    if (_size[_root[x]] < _size[_root[y]])
      swap(x, y);
    _size[_root[x]] += _size[_root[y]];
    _node[_root[x]].push_back(_root[y]);
    _ch_root(_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);
    }
  }
}