堆实现最优队列

最优队列就是靠堆实现的,普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (largest-in,first-out)的行为特征。也就最优队列可以保证队头一定是有限度最大的元素。一个优先队列一般满足以下几个操作:

INSERT(S,x):把元素x插入集合S中

MAXIMUM(S):返回S中具有最大关键字的元素

EXTRACT-MAX(S):去掉并返回S中具有最大关键字的元素

INCREASE-KEY(S,x,k):将元素x的关键字增加到k,这里假设k的值不小于x的关键字值


#include<iostream>
#include<algorithm>
#define maxsize 5000
using namespace std;
int heapsize;

int HeapMaximum(int a[])//返回优先队列中关键字最大的元素
{
	return a[1];
}
void MaxHeapify(int a[], int i)//维护最大堆
{
	int left = 2 * i;
	int right = 2 * i + 1;
	int largest;
	if (left<=heapsize&&a[i] < a[left])
		largest = left;
	else
		largest = i;
	if (right<=heapsize&&a[largest] < a[right])
		largest = right;
	if (largest != i)
	{
		swap(a[i], a[largest]);
		MaxHeapify(a,largest);
	}
}
int HeapExtractMax(int a[])//去掉并返回关键字最大的元素
{
	if (heapsize < 1)
		cout << "error:heap underflow" << endl;
	int max = a[1];
	a[1] = a[heapsize];
	heapsize--;
	MaxHeapify(a, 1);
	return max;
}
void HeapIncreaseKey(int a[], int i, int key)//将元素x的关键字增加为key,这里假设key的值不小于原值
{
	if (key < a[i])
		cout << "error:new key is smaller than current key" << endl;
	a[i] = key;
	while (i > 1 && a[i / 2] < a[i])
	{
		swap(a[i], a[i / 2]);
		i = i / 2;
	}
}
void MaxHeapInsert(int a[], int key)//往优先队列中插入一个关键字为key的元素
{
	heapsize++;
	a[heapsize] = -0xfffffff;//先增加一个关键字为负无穷的叶节点
	HeapIncreaseKey(a, heapsize, key);
}

int main()
{
	int n;
	int key[maxsize],heap[maxsize];
	cin >> n;
	heapsize = 0;
	for (int i = 1; i <= n; i++)
	{
		cin >> key[i];
		MaxHeapInsert(heap, key[i]);
	}
	cout << "max is : " << HeapMaximum(heap) << endl;
	cout << "heapsize is : " << heapsize << endl;
	cout << "drop an item and then the max is : " << HeapExtractMax(heap) << endl;
	cout << "heapsize is : " << heapsize << endl;
	for (int i = 1; i <= heapsize; i++)
		cout << heap[i] << " ";
	cout << endl;
	cout << "change the third item's key" << endl;
	HeapIncreaseKey(heap, 3, 100);
	for (int i = 1; i <= heapsize; i++)
		cout << heap[i] << " ";
	cout << endl;
	cout << "max is : " << HeapMaximum(heap) << endl;
	return 0;
}




posted @ 2016-07-18 22:34  seasonal  阅读(253)  评论(0编辑  收藏  举报