建堆之后堆顶是几
把 17 24 15 13 23 建成大顶堆。
运行下面这段程序:
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace std;
void sift_down(vector<int>& h, int i, int n) {
while (true) {
int big = i;
int l = 2 * i + 1, 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;
}
}
vector<int> hsort(vector<int> h) {
int n = (int)h.size();
for (int i = n / 2 - 1; i >= 0; i--) sift_down(h, i, n);
for (int end = n - 1; end > 0; end--) {
swap(h[0], h[end]);
sift_down(h, 0, end);
}
return h;
}
int main() {
vector<int> h = {17, 24, 15, 13, 23};
int n = (int)h.size();
for (int i = n / 2 - 1; i >= 0; i--) sift_down(h, i, n);
cout << h[0] << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)