#include <iostream>
#include <string>
#include <vector>
using namespace std ;
template <typename T>
class myHeap {
private :
vector<T> heap ;
void swap(T &a, T &b) {
T temp = a ;
a = b ;
b = temp ;
}
void down_adjust(int root) {
int l = 2 * root + 1 ;
int r = 2 * root + 2 ;
int mx = root ;
if (l < heap.size() && heap[l] > heap[mx]) mx = l ;
if (r < heap.size() && heap[r] > heap[mx]) mx = r ;
if (mx != root) {
swap(heap[mx], heap[root]) ;
down_adjust(mx) ;
}
}
void up_adjust() {
int last = heap.size() - 1 ;
int root = (last - 1) / 2 ;
while (root >= 0 && heap[last] > heap[root]) {
swap(heap[last], heap[root]) ;
last = root ;
root = (root - 1) / 2 ;
}
}
void construct() {
for (int i = (heap.size() - 2) / 2 ; i >= 0 ; i -- ) {
down_adjust(i) ;
}
}
public :
void push(T val) {
heap.push_back(val) ;
up_adjust() ;
}
T pop() {
T temp = heap[0] ;
heap[0] = heap.back() ;
heap.pop_back() ;
down_adjust(0) ;
return temp ;
}
T top() {
return heap[0] ;
}
bool empty() {
return heap.size() == 0 ;
}
};
int main() {
int n ;
cin >> n ;
string op ;
int val ;
myHeap<int> heap ;
for (int i = 0 ; i < n ; i ++ ) {
cin >> op ;
if (op == "push") {
cin >> val ;
heap.push(val) ;
}
else if (op == "pop") {
if (heap.empty()) cout << "empty" << endl ;
else cout << heap.pop() << endl ;
}
else if (op == "top") {
if (heap.empty()) cout << "empty" << endl ;
else cout << heap.top() << endl ;
}
}
return 0 ;
}
C++数据结构:大根堆模板
最新推荐文章于 2025-01-27 00:15:00 发布