简体   繁体   English

配对堆-减少密钥的实现

[英]Pairing heap - implementation of decrease key

I just implemented the pairing heap data structure. 我刚刚实现了配对堆数据结构。 Pairing heap supports insert, find-min, merge in O(1) amortized time and delete, delete-min in O(logN) amortized time. 配对堆支持在O(1)摊销时间内插入,查找最小,合并,并在O(logN)摊销时间内删除,删除最小。 But the most remarkable operation is the decrease-key, which has complexity O(log logN). 但是最显着的操作是减少键,它具有复杂度O(log logN)。 More about pairing heaps can be found at http://en.wikipedia.org/wiki/Pairing_heap . 有关配对堆的更多信息,请访问http://en.wikipedia.org/wiki/Pairing_heap

I have implemented the insert, merge, and delete-min operations, but the wikipedia article didn't say how to decrease a key of a given node, so I couldn't implement it. 我已经实现了insert,merge和delete-min操作,但是Wikipedia文章并未说明如何减少给定节点的键,因此无法实现。 Could someone tell me how it actually works? 有人可以告诉我它是如何工作的吗?

Here is my code: 这是我的代码:

template< class key_t, class compare_t=std::less< key_t > >
struct pairing_heap {
private:
  struct node { 
    key_t key; std::vector< node* > c;
    node( key_t k=key_t() ) : key( k ), c( std::vector< node* >() ) {}
  };
  node *root;
  compare_t cmp;
  unsigned sz;
public:
  typedef key_t value_type;
  typedef compare_t compare_type;
  typedef pairing_heap< key_t, compare_t > self_type;

  pairing_heap() : root( 0 ) {}
  node* merge( node *x, node *y ) {
    if( !x ) return y;
    else if( !y ) return x;
    else {
      if( cmp( x->key, y->key ) ) {
        x->c.push_back( y );
        return x;
      } else {
        y->c.push_back( x );
        return y;
      }
    }
  }
  node* merge_pairs( std::vector< node* > &c, unsigned i ) {
    if( c.size()==0 || i>=c.size() ) return 0;
    else if( i==c.size()-1 ) return c[ i ];
    else {
      return merge( merge( c[ i ], c[ i+1 ] ), merge_pairs( c, i+2 ) );
    }
  }
  void insert( key_t x ) {
    root = merge( root, new node( x ) );
    sz++;
  }
  key_t delmin() {
    if( !root ) throw std::runtime_error( "std::runtime_error" );
    key_t ret=root->key;
    root = merge_pairs( root->c, 0 );
    sz--;
    return ret;
  }
  bool empty() const { return root==0; }
  unsigned size() const { return sz; }
};

According to the original paper on pairing heaps, page 114 , the decrease-key operation is implemented as follows. 根据有关配对堆的原始文章(第114页) ,减小键操作实现如下。 First, change the priority of the node whose key is to be decreased to have the new priority. 首先,将要减小其密钥的节点的优先级更改为具有新的优先级。 If its priority is still greater than its parent (or if it's the root of the tree), you are done. 如果它的优先级仍然大于其父级(或者它是树的根),那么就完成了。 Otherwise, cut the link from that node to its parent, then use the merge operation to combine the original heap with the subtree that was just cut from that tree. 否则,请剪切从该节点到其父节点的链接,然后使用合并操作将原始堆与刚从该树剪切的子树合并。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM