1. 程式人生 > >算法庫中heap應用

算法庫中heap應用

cout .so out cto vector == i++ 是把 mman

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

算法庫中heap應用