struct node{
int val;
int len; // 最短路径长度
node *lc,*rc;
node(int a,int b,int c) {
val = a;
siz = b;
len = c;
lc = NULL;
rc = NULL;
}
};
void update(node *a) { // 更新当前节点信息
node *l = a->lc;
node *r = a->rc;
int len1 = 0;
int len2 = 0;
if (l != NULL) len1 = l->len;
if (r != NULL) len2 = r->len;
if (len1 < len2) { // 如果左子树的最短路径短,则交换左右子树,保持左式堆性质
node *tmp = a->lc;
a->lc = a->rc;
a->rc = tmp;
}
a->len = (len1 < len2 ? len1 : len2) + 1; // 取子树最短路径加1
}
node* merge(node *a,node *b) { // 合并两个堆
if (a == NULL) return b;
if (b == NULL) return a;
if (a->val < b->val) { // 如果a的根节点小,那么合并a的右子树和b作为合并后树的右子树
a->rc = merge(a->rc, b);
update(a); // 更新a
return a; // 返回a
}else {
b->rc = merge(a,b->rc);
update(b);
return b;
}
}
node* remove(node *a) { // 去掉最小元素
return merge(a->lc, a->rc); // 将左子树和右子树合并返回即可
}
左式堆代码
最新推荐文章于 2023-02-06 14:29:43 发布