算法库中heap应用

STL中make_heap 的接口为:

 

default (1)
template <class RandomAccessIterator>
  void make_heap (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template <class RandomAccessIterator, class Compare>
  void make_heap (RandomAccessIterator first, RandomAccessIterator last,
                  Compare comp );

默认的使用operator< 进行比较。而我们可以自定义comp进行比较,来进行建堆。

 

其中,两个make_heap所使用的参数,[first,last)     这个区间是半开半闭的。

 

 

当我们需要对堆进行存取操作时,我们有函数,pos_heap,push_heap

 

default (1)
template <class RandomAccessIterator>
  void pop_heap (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template <class RandomAccessIterator, class Compare>
  void pop_heap (RandomAccessIterator first, RandomAccessIterator last,
                 Compare comp);



使用pop_heap 操作后, 最大值被移动到last-1的位置。[first ,last-1) 之间的元素继续保持堆的形态。

 

我们只需取出最后一个元素即可。也就是vec.pop_back();

default (1)
template <class RandomAccessIterator>
  void push_heap (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template <class RandomAccessIterator, class Compare>
  void push_heap (RandomAccessIterator first, RandomAccessIterator last,
                   Compare comp);

执行push_heap 时, [first,last-1)个元素是保持堆形态的,如果不是堆,则会报错。

 

这个函数是相当于对堆进行调整。

 

Code:

 


#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<vector>
using namespace std;
vector heap;
int n;
int main()
{
	cout<<"Insert numbers of heap:";
	cin>>n;
	cout<<"Insert values of each members:\n";
	for(int i=0;i<n;i++)
	{
		int read;
		cin>>read;
		heap.push_back(read);
	}
	make_heap(heap.begin(),heap.end());//大根堆
	//make_heap(heap.begin(),heap.end(),greater());小根堆
	cout<<"If there's something trouble,insert \"help\"!\n";
	cout<<"Heap has neen maken!\nPlease insert commands:\n";
	while(1)
	{
		string s;
		cin>>s;
		if(s=="pop")
		{
			pop_heap(heap.begin(),heap.end());
			cout<<heap[heap.size()-1];
			heap.pop_back();
			cout<<endl;
		}
		else if(s=="push")
		{
			int read;
			cin>>read;
			heap.push_back(read);
			push_heap(heap.begin(),heap.end());
		}
		else if(s=="top")
		{
			cout<<heap.front()<<endl;
		}
		else if(s=="sort")//奇怪的是,这里大根堆的堆排序是由小到大的(就是把数列逆转了)
		{
			vector temp;
			temp=heap;
			sort_heap(temp.begin(),temp.end());
			for(int i=0;i<temp.size();i++)
			cout<<temp[i]<<' ';
			cout<<endl;
		}
		else if(s=="out")
		{
			for(int i=0;i<heap.size();i++)
			cout<<heap[i]<<' ';
			cout<<endl;
		}
 		else if(s=="end")
		{
			return 0;
		}
		else if(s=="help")
		{
			cout<<"1.Pop the top number of heap,please insert \"pop\"!\n";
			cout<<"2.Push a number into heap,please insert \"push numbers\"!\n";
			cout<<"3.Look the top number of heap,please insert \"top\"!\n";
			cout<<"4.Sort the heap and import result,please insert \"sort\"!\n";
			cout<<"5.Look the array of heap,please insert \"out\"!\n";
			cout<<"6.End the program,please insert \"end\"!\n";
		}
		else
		cout<<"Bad Commands!"<<endl;
	}
	return 0;
} 
posted @ 2017-06-24 19:09  银河渡舟  阅读(231)  评论(0编辑  收藏  举报