跳到正文

个人记录

P1001 A+B problem 题解

Acceptedit_约 2 分钟
原文
文章信息与版本

文章信息

发布
2023年6月29日
收录
2026年8月20日
更新
2026年11月6日
篇幅
约 2 分钟
获赞
36

版本

  1. v1当前

一道练习二叉堆的好题!!

话不多说,直接上代码:

C++
#include <bits/stdc++.h>
using namespace std;

const int maxn = 1000010;
int w[maxn], tot, a, b, ans;

int top() {
    return w[1]; // 返回根节点
}

void modify(int x) { // 插入时自底向上修复 x 号节点
    if(x == 1 || w[x] > w[x / 2]) return; // x 已经是根或符合小根堆性质
    swap(w[x], w[x / 2]);
    modify(x / 2); // 递归继续修复
}
void push(int x) { // 插入元素 x
    w[++tot] = x; // 直接插到尾部
    modify(tot); // 修复
}

void repair(int x) { // 删除时自上而下修复 x 号节点
    if(x * 2 > tot) return; // 已经是叶子节点
    int tar = x * 2; // 右节点一定存在
    if(x * 2 + 1 <= tot) tar = w[x * 2] < w[x * 2 + 1] ? x * 2 : x * 2 + 1;
    // 如果有左节点,tar 取两节点的最小值
    if(w[x] < w[tar]) return; // 不违反小根堆性质说明修复成功,返回
    swap(w[x], w[tar]); // 否则和小的交换
    repair(tar); // 继续修复
}
void pop() { // 弹掉最小值
    swap(w[1], w[tot--]); // 压行技巧,交换尾部节点并将尾节点设为无效
    repair(1); // 从根节点修复
}

int main() {
    cin >> a >> b;
    push(a);
    push(b); // 输入的数加入堆
    while(tot) {
        ans += top();
        pop(); // 每次加上堆中的第一个数并弹掉
    }
    cout << ans; // 输出
    return 0;
}

祝大家也 AC 愉快!!