优先队列的原理就是堆。
默认的优先队列是最小二叉堆。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
struct data
{
int x,y;
data(int x,int y){
this->x=x;
this->y=y;
}
friend bool operator<(data a,data b)
{
if(a.x==b.x)
return a.y>b.y;
return a.x>b.x;
}
};
struct cmp1{
bool operator()(int x,int y)
{
return x<y;
}
};
int x;
int main()
{
priority_queue<data>q1;
priority_queue<int,vector<int>,cmp1>q_int;
printf("-----结构体优先队列---------\n");
int n, x, y;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d%d",&x,&y);
q1.push(data(x,y));
}
while(!q1.empty()){
data tmp = q1.top();
printf("%d %d\n",tmp.x,tmp.y);
q1.pop();
}
printf("----简单的数据类型优先队列---------\n");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&x);
q_int.push(x);
}
while(!q_int.empty())
{
x = q_int.top();
printf("%d ",x);
q_int.pop();
}
printf("\n");
}
Output:
-----结构体优先队列---------
4
1 2
3 4
3 3
2 2
1 2
2 2
3 3
3 4
----简单的数据类型优先队列---------
4
1 2 3 4
4 3 2 1
Process returned 0 (0x0) execution time : 10.309 s
Press any key to continue.