c++的STL中堆的运用

STL中的建立的队默认是最大堆,要想用最小堆的话,必须要在push_heap,pop_heap,make_heap等每一个函数后面加第三个参数greater<int>(),括号不能省略

make_heap(_First, _Last, _Comp); //默认是建立最大堆的。对int类型,可以在第三个参数传入greater<int>()得到最小堆。
push_heap (_First, _Last); //在堆中添加数据,要先在容器中加入数据,再调用push_heap ()
pop_heap(_First, _Last); //在堆中删除数据,要先调用pop_heap()再在容器中删除数据
sort_heap(_First, _Last); //堆排序,排序之后就不再是一个合法的heap了


//堆的基本操作举例

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main () {
  int a[] = {1,2,3,5,6};
  vector<int> v(a, a + sizeof(a)/sizeof(a[0]));

  make_heap(v.begin(),v.end());
  cout << "initial max of heap   : " << v.front() << endl;

  pop_heap(v.begin(),v.end()); v.pop_back();
  cout << "max of heap after pop : " << v.front() << endl;

  v.push_back(7); push_heap(v.begin(),v.end());
  cout << "max of heap after push: " << v.front() << endl;

  sort_heap (v.begin(),v.end());

  cout << "sorted range :";
  for (unsigned i=0; i<v.size(); i++) 
  		cout << " " << v[i];


  return 0;
}
//利用堆的基本操作返回给出序列的最小的K个数字
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <set>

using namespace std;
   
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> v;
        
        make_heap(input.begin(), input.end(), greater<int>());
        for(int i = 1; i <= k; ++i)
        {
            v.push_back(input.front());
            pop_heap(input.begin(), input.end(), greater<int>());
            input.pop_back();
        }
        
        return v;
    } 

int main()
{
	vector<int> v;
	
	int n, m;
	cin >> n;
	for(int i = 0; i < n; ++i)
	{
		cin >> m;
		v.push_back(m);
	}
	
	vector<int> q = GetLeastNumbers_Solution(v, 2);
	
	for(int i = 0; i < q.size(); ++i)
	{
		cout << q[i];
	}
	
	return 0;
} 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值