#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
template<class T>
class priority_queue {
public:
int size() {
return hvec.size();
}
bool empty() {
return hvec.empty();
}
//向上重新建堆
void push(const T& nval) {
hvec.push_back(nval);
int child = hvec.size()-1;
int parent = (child-1)/2;
while(parent >= 0 && hvec[parent] < hvec[child]) {
swap(hvec[parent], hvec[child]);
child = parent;
parent = (child-1)/2;
}
}
//向下重新建堆,优先级最高的先出列
void pop() {
assert(!hvec.empty());
swap(hvec[0], hvec[size()-1]);
hvec.pop_back();
int root_index = 0;
int l_index = 2 * root_index +1;
int r_index = 2 * root_index +2;
while(l_index < hvec.size()) {
if(r_index < hvec.size()) { //有右孩子
T tmp = max(hvec[root_index], hvec[l_index], hvec[r_index]);
if(tmp == hvec[root_index])
break;
else if(tmp == hvec[l_index]) {
swap(hvec[l_index], hvec[root_index]);
root_index = l_index;
}
else {
swap(hvec[r_index], hvec[root_index]);
root_index = r_index;
}
}
//无右孩子
else {
if(hvec[root_index] >= hvec[l_index])
break;
else {
swap(hvec[l_index], hvec[root_index]);
root_index = l_index;
}
}
l_index = 2 * root_index +1;
r_index = 2 * root_index +2;
}
}
T top() {
assert(!hvec.empty());
return hvec[0];
}
private:
vector<T> hvec;
void swap(T &a, T &b) {
T tmp;
tmp = a;
a = b;
b = tmp;
}
T max(T &a, T &b, T &c) {
T tmp = (a > b) ? a : b;
return (tmp > c) ? tmp : c;
}
};
int main() {
priority_queue<int> pq;
pq.push(21);
cout << pq.top() << endl;
pq.push(35);
cout << pq.top() << endl;
pq.push(4);
cout << pq.top() << endl;
pq.push(22);
cout << pq.top() << endl;
pq.push(5);
cout << pq.top() << endl;
pq.push(19);
cout << pq.top() << endl;
pq.push(27);
cout << pq.top() << endl;
pq.push(45);
cout << pq.top() << endl;
pq.push(23);
cout << pq.top() << endl;
pq.push(42);
cout << pq.top() << endl;
while(!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
cout << endl;
return 0;
}
使用vector实现优先队列
最新推荐文章于 2024-07-23 17:19:21 发布