前三大是哪几个

👁️ 0 人浏览 💬 0 人评论 ❤️ 添加收藏

同一个堆。运行下面这段程序:

#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;

string join(const vector<int>& v) {
    string s;
    for (size_t i = 0; i < v.size(); i++) s += (i ? "/" : "") + to_string(v[i]);
    return s;
}

void sift_down(vector<int>& h, int i, int n) {
    while (true) {
        int big = i;
        int l = 2 * i + 1;
        int r = 2 * i + 2;
        if (l < n && h[l] > h[big]) big = l;
        if (r < n && h[r] > h[big]) big = r;
        if (big == i) return;
        swap(h[i], h[big]);
        i = big;
    }
}

int pop_top(vector<int>& h) {
    int top = h[0];
    int last = h.back();
    h.pop_back();
    if (!h.empty()) {
        h[0] = last;
        sift_down(h, 0, (int)h.size());
    }
    return top;
}

int main() {
    vector<int> h = {24, 23, 15, 13, 17};
    vector<int> out;
    for (int k = 0; k < 3; k++) out.push_back(pop_top(h));
    cout << join(out) << endl;
}

(本题用 g++ -std=c++17 -O0 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论