Advertisement
froleyks

dynamic_connectivity.cpp

Dec 5th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include "dynamic_connectivity.hpp"
  2. #include <iomanip>
  3. #include <iostream>
  4.  
  5. DynamicConnectivity::DynamicConnectivity() {
  6. }
  7.  
  8. DynamicConnectivity::DynamicConnectivity(long num_nodes) {
  9.   union_find = new std::atomic<Node>[num_nodes];
  10.   for (int i = 0; i < num_nodes; ++i) {
  11.     union_find[i] = i;
  12.   }
  13. }
  14.  
  15. void DynamicConnectivity::printUF() {
  16.   for (int i = 0; i < 9; ++i) {
  17.     std::cout << i << ": " << union_find[i] << std::endl;
  18.   }
  19.   std::cout << std::endl;
  20. }
  21.  
  22. void DynamicConnectivity::addEdges(const EdgeList &edges) {
  23.   for (auto [from, to, length] : edges) {
  24.     std::cout << std::setw(2) << from << " | " << std::setw(2) << to
  25.               << std::endl;
  26.     union_find[find_representative(from)] = find_representative(to);
  27.     printUF();
  28.   }
  29. }
  30.  
  31. bool DynamicConnectivity::connected(Node a, Node b) const {
  32.   return find_representative(a) == find_representative(b);
  33. }
  34.  
  35. DynamicConnectivity::Node DynamicConnectivity::parentOf(Node n) const {
  36.   return union_find[n];
  37. }
  38.  
  39. DynamicConnectivity::Node
  40. DynamicConnectivity::find_representative(Node a) const {
  41.   Node current = a;
  42.   Node parent = union_find[current];
  43.  
  44.   while (current != parent) {
  45.     current = parent;
  46.     parent = union_find[current];
  47.   }
  48.  
  49.   return parent;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement