前三大是哪几个
同一个堆。运行下面这段程序:
#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 编译。)
全部评论