文章

15

粉丝

142

获赞

25

访问

13.4k

头像
堆的判断 题解:
P1127
发布于2023年5月4日 15:51
阅读数 536

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;

int n;
int h[N], cnt, flag; // h 存储堆,cnt 为堆大小,flag 标记是否建成

void down(int u){ // 向下调整操作,参数u为需要向下调整的节点编号
    int t=u; // 用于记录需要交换的节点编号
    if (2*u <= cnt && h[2*u] < h[u]) t=2*u; // 若左子节点存在且小于当前节点,则记录左子节点编号
    if (2*u+1 <= cnt && h[t] > h[2*u+1]) t=2*u+1; // 若右子节点存在且小于当前节点和左子节点,则记录右子节点编号
    if (t!=u){ // 如果需要交换
        flag = 1; // 标记为还未建成
        swap(h[u],h[t]); // 交换当前节点和需要交换的节点
        down(t); // 递归向下调整
    }
}

int main(){
    cin >> n;
    for (int i = 1; i <= n; i++) {
        scanf("%d",&h[i]);
        cnt++; // 统计堆大小
 &n...

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发