使用vector实现优先队列

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值