优先队列一般默认数的优先级是大的先放,然而想要小的数先放进去的话就得重载,
如
priority_queue<int ,vector<int>,mycmp>pq;
struct mycmp//priority_queue一般默认是按从大到小排列的,要从小到大的话就要这个来改变了,a>b是从小到大,即pq.top()是最小的元素,a<b则相反
{
bool operator()(const int &a,const int &b)
{
return a>b;
}
};
或者用#include< functional >里面的函数greater,使得优先级是从大到小,使用less,优先级是从小到大了;
如:
priority_queue<int,vector<int>,less<int>>pq;//大
priority_queue<int,vector<int>,greater<int>>pq;//小
poj5939
题目是要用堆去做,但是没学过数据结构,不会。
所以就想采用STL来做了,根据题意,我们需要一个有顺序的容器,set有从小到大的功能,但是set不能有重复元素,所以放弃;map是两个元素,所以也放弃;所以后面就采用了优先队列了;
题意:
定义一个数组,初始化为空。在数组上执行两种操作:
1、增添1个元素,把1个新的元素放入数组。
2、输出并删除数组中最小的数。
使用堆结构实现上述功能的高效算法。
输入
第一行输入一个整数t,代表测试数据的组数。
对于每组测试数据,第一行输入一个整数n,代表操作的次数。
每次操作首先输入一个整数type。
当type=1,增添操作,接着输入一个整数u,代表要插入的元素。
当type=2,输出删除操作,输出并删除数组中最小的元素。
1<=n<=100000。
输出
每次删除操作输出被删除的数字。
我的:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <iomanip>
#include <list>
#include <queue>
#include <stack>
using namespace std;
const int maxn=10010;
struct mycmp//priority_queue一般默认是按从大到小排列的,要从小到大的话就要这个来改变了,a>b是从小到大,即pq.top()是最小的元素,a<b则相反
{
bool operator()(const int &a,const int &b)
{
return a>b;
}
};
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
priority_queue<int ,vector<int>,mycmp>pq;
while(n--)
{
int work;
cin>>work;
if(work==1)
{
int x;
cin>>x;
pq.push(x);
}
else if(work==2)
{
cout<<pq.top()<<endl;
pq.pop();
}
}
}
return 0;
}