Advertisement
froleyks

dynamic_connectivity.cpp

Dec 5th, 2018
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 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.   component_size = new std::atomic<uint>[num_nodes];
  15.   for (int i = 0; i < num_nodes; ++i) {
  16.     component_size[i] = 1;
  17.   }
  18. }
  19.  
  20. void DynamicConnectivity::printUF() {
  21.   for (int i = 0; i < 9; ++i) {
  22.     std::cout << i << ": " << union_find[i] << std::endl;
  23.   }
  24.   std::cout << std::endl;
  25. }
  26.  
  27. void DynamicConnectivity::addEdges(const EdgeList &edges) {
  28.   for (auto [from, to, length] : edges) {
  29.     // std::cout << std::setw(2) << from << " | " << std::setw(2) << to
  30.     //           << std::endl;
  31.  
  32.     // find bigger component
  33.     Node root_from = find_representative(from);
  34.     Node root_to = find_representative(to);
  35.  
  36.     if (component_size[root_from] > component_size[root_to]) {
  37.       union_find[root_to] = root_from;
  38.       component_size[root_from] += component_size[root_to];
  39.     }else{
  40.       union_find[root_from] = root_to;
  41.       component_size[root_to] += component_size[root_from];
  42.     }
  43.  
  44.     // union_find[find_representative(from)] = find_representative(to);
  45.     // printUF();
  46.   }
  47. }
  48.  
  49. bool DynamicConnectivity::connected(Node a, Node b) const {
  50.   return find_representative(a) == find_representative(b);
  51. }
  52.  
  53. DynamicConnectivity::Node DynamicConnectivity::parentOf(Node n) const {
  54.   return union_find[n];
  55. }
  56.  
  57. DynamicConnectivity::Node
  58. DynamicConnectivity::find_representative(Node a) const {
  59.   Node current = a;
  60.   Node parent = union_find[current];
  61.  
  62.   while (current != parent) {
  63.     current = parent;
  64.     parent = union_find[current];
  65.   }
  66.  
  67.   // path compression
  68.   Node representative = parent;
  69.   current = a;
  70.   parent = union_find[current];
  71.   while (current != parent) {
  72.     union_find[current] = representative;
  73.     current = parent;
  74.     parent = union_find[current];
  75.   }
  76.  
  77.  
  78.   return parent;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement