我刚刚实现了配对堆数据结构。配对堆支持 O(1) 分摊时间的插入、查找、合并和 O(logN) 分摊时间的删除、删除。但最引人注目的操作是减少键,其复杂度为 O(log logN)。有关配对堆的更多信息,请访问 http://en.wikipedia.org/wiki/Pairing_heap。 .
我已经实现了insert,merge,delete-min操作,但是wikipedia文章没有说如何减少给定节点的key,所以我无法实现。谁能告诉我它实际上是如何工作的?
这是我的代码:
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; }
};
最佳答案
根据 the original paper on pairing heaps, page 114 ,减键操作实现如下。首先,将要减少其关键字的节点的优先级更改为具有新的优先级。如果它的优先级仍然大于它的父级(或者如果它是树的根),你就完成了。否则,切断从该节点到其父节点的链接,然后使用合并操作将原始堆与刚刚从该树中切断的子树合并。
希望这对您有所帮助!
关于c++ - 配对堆——递减键的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13940044/