做题步骤
- 感觉到这题是模拟题,当然也许你可以直接用优先队列😁
- 从AI那知道堆是完全二叉树的结构,但是感觉这样模拟好麻烦
- 看了题解发现别人也是这样做的,然后……
代码:
// #牛客春招刷题训练营# https://www.nowcoder.com/discuss/726480854079250432
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
class hv_heap{
private:
int size = 0;
vector<T> tree;
void ppush(T x){
size++;
tree.emplace_back(x);
int last = size - 1;
int root = (last - 1) / 2;
while(tree[root] < tree[last]){
swap(tree[root], tree[last]);
last = root;
root = (last - 1) / 2;
}
}
bool empty(){
return size <= 0;
}
void down(int root){
int left = root * 2 + 1,
right = root * 2 + 2,
maxroot = root;
if (left < size && tree[left] > tree[maxroot]) maxroot = left;
if (right < size && tree[right] > tree[maxroot]) maxroot = right;
if (maxroot != root){
swap(tree[maxroot], tree[root]);
down(maxroot);
}
}
void ppop(){
if (empty()) cout << "empty\n";
else {
cout << tree[0] << "\n";
tree[0] = tree.back();
tree.pop_back();
size--;
down(0);
}
}
public:
void push(T x){
ppush(x);
}
void top(){
if (empty()) cout << "empty\n";
else cout << tree[0] << "\n";
}
void pop(){
ppop();
}
};
int main() {
ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
hv_heap<int> heap;
int n, x;
cin >> n;
string s;
while(n--){
cin >> s;
if (s == "push"){
cin >> x;
heap.push(x);
}
else if (s == "top"){
heap.top();
}
else if (s == "pop"){
heap.pop();
}
}
return 0;
}
// 64 位输出请用 printf("%lld")