smatskevich

DSU

May 26th, 2018
147
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. class DSU {
  5. public:
  6.     explicit DSU( int n );
  7.  
  8.     int Find( int u );
  9.     void Merge( int u, int v );
  10.  
  11. private:
  12.     std::vector<int> parent;
  13.     std::vector<int> rank; // Ранги узлов. Глубина дереве не больше ранга.
  14. };
  15.  
  16. DSU::DSU( int n ) :
  17.     parent( n ),
  18.     rank( n, 1 )
  19. {
  20.     for( int i = 0; i < n; ++i ) {
  21.         parent[i] = i;
  22.     }
  23. }
  24.  
  25. int DSU::Find( int u )
  26. {
  27.     if( parent[u] == u ) {
  28.         return u;
  29.     }
  30.     // Сжатие пути.
  31.     return parent[u] = Find( parent[u] );
  32. }
  33.  
  34. void DSU::Merge( int u, int v )
  35. {
  36.     const int rootU = Find( u );
  37.     const int rootV = Find( v );
  38.     if( rank[rootU] < rank[rootV] ) {
  39.         parent[rootU] = rootV;
  40.     } else {
  41.         if( rank[rootU] == rank[rootV] ) {
  42.             ++rank[rootU];
  43.         }
  44.         parent[rootV] = rootU;
  45.     }
  46. }
  47.  
  48. int main()
  49. {
  50.     DSU dsu( 5 );
  51.     std::cout << ( dsu.Find( 0 ) != dsu.Find( 2 ) ? "OK" : "FAIL" ) << std::endl;
  52.     dsu.Merge( 0, 2 );
  53.     std::cout << ( dsu.Find( 0 ) == dsu.Find( 2 ) ? "OK" : "FAIL" ) << std::endl;
  54.     dsu.Merge( 4, 2 );
  55.     std::cout << ( dsu.Find( 0 ) == dsu.Find( 4 ) ? "OK" : "FAIL" ) << std::endl;
  56.     dsu.Merge( 1, 3 );
  57.     std::cout << ( dsu.Find( 1 ) == dsu.Find( 3 ) ? "OK" : "FAIL" ) << std::endl;
  58.     std::cout << ( dsu.Find( 1 ) != dsu.Find( 4 ) ? "OK" : "FAIL" ) << std::endl;
  59.     dsu.Merge( 1, 4 );
  60.     std::cout << ( dsu.Find( 1 ) == dsu.Find( 4 ) ? "OK" : "FAIL" ) << std::endl;
  61.     return 0;
  62. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×