# 点击这里了解什么是priority_queue

## 前言

priority_queue默认是大根堆，也就是大的元素会放在前面

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
priority_queue<int>q;
int a[15]={0,1,4,2,3,5};
const int n=5;
int main()
{
for(int i=1;i<=n;i++)    q.push(a[i]);
while(q.size()!=0)
printf("%d ",q.top()),q.pop();
return 0;
}

## 方法一

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
priority_queue<int>q;
int a[15]={0,1,4,2,3,5};
const int n=5;
int main()
{
for(int i=1;i<=n;i++)    q.push(-a[i]);
while(q.size()!=0)
printf("%d ",-q.top()),q.pop();
return 0;
}

## 方法二

就好

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
priority_queue<int,vector<int>,greater<int> >q;//这样就可以实现小根堆了
int a[15]={0,1,4,2,3,5};
const int n=5;
int main()
{
for(int i=1;i<=n;i++)    q.push(a[i]);
while(q.size()!=0)
printf("%d ",q.top()),q.pop();
return 0;
}

## 另外

priority_queue是支持自定义比较函数的

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int n=5;
struct node
{
int x,y;
node(){x=y=0;}
node(int a,int b){x=a;y=b;}
};
priority_queue<node>q;
bool operator<(const node &a,const node &b)
{
if(a.x!=b.x)return a.x>b.x;
return a.y<b.y;
}
int a[15]={0,1,4,4,3,5};
int b[15]={0,2,1,2,3,4};
int main()
{
for(int i=1;i<=n;i++)    q.push(node(a[i],b[i]));
while(q.size()!=0)
printf("%d %d\n",q.top().x,q.top().y),q.pop();
return 0;
}

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int n=5;
struct node
{
int x,y;
node(){x=y=0;}
node(int a,int b){x=a;y=b;}
bool operator <(const node &a)const
{
if(a.x!=x) return a.x<x;
return a.y>y;
}
};
priority_queue<node>q;
int a[15]={0,1,4,4,3,5};
int b[15]={0,2,1,2,3,4};
int main()
{
for(int i=1;i<=n;i++)    q.push(node(a[i],b[i]));
while(q.size()!=0)
printf("%d %d\n",q.top().x,q.top().y),q.pop();
return 0;
}

posted @ 2017-11-07 19:22  自为风月马前卒  阅读(...)  评论(...编辑  收藏

……