堆【STL】

堆【STL—优先队列】

洛谷P3378

P.S. stl用法大全

需要用到的头文件

#include<queue>

定义一个堆

priority_queue<类型>name;

P.S. 定义的堆默认为大根堆,要定义小根堆可以

priority_queue<int,vector<类型>,greater<类型> >name;

堆的基本操作

q.push(x);      //插入元素“x”
q.empty();     //返回堆是否为空(返回值为布尔型)
q.top()       //返回堆顶元素(不弹出)
q.pop()      //弹出堆顶元素(不返回)
q.size()    //返回堆的大小

模版的代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>

using namespace std;

priority_queue<int,vector<int>,greater<int> >heap;

int n,k,z,num;

int main()
{
	scanf("%d",&n);
	while(n --)
	{
		scanf("%d",&k);
		if(k == 1)
		{
			scanf("%d",&num);
			heap.push(num);
		}
		if(k == 2)
		{
			num = heap.top();
			printf("%d\n",num);
		}
		if(k == 3)
		{
			heap.pop();
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Mr_S_Edward/article/details/82949272