傳送門
優(yōu)先隊列在語法(推入,刪除)上與普通隊列一樣,不同在于聲明時要這樣:priority_queue<int,vector<int>,greater<int> >q;
優(yōu)先隊列中默認出來的top值為該隊列中的最小的數(shù).這道題就是一道模擬優(yōu)先隊列的題.(被人看來是水題,而我卻。)
代碼如下:
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int maxn=1000005;
struct node
{
char ch;
int x;
}op[maxn];
int main()
{
priority_queue<int,vector<int>,greater<int> >q;//優(yōu)先隊列的嚴格聲明方式.
int n,i,k=0,u;//默認該隊列中最小的數(shù)為優(yōu)先級最高的數(shù),即q.top=q.min.
char s[10];
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s",s);
if(s[0]=='i')
{
scanf("%d",&u);
op[k].x=u;
op[k++].ch='i';
q.push(u);
}
else if(s[0]=='r')
{
if(q.empty()){//防止隊列為空時,該操作非法;
op[k].x=0;
op[k++].ch='i';
q.push(0);
}
q.pop();
op[k++].ch='r';
}
else{
scanf("%d",&u);//u就是目標數(shù).
if(!q.empty()&&q.top()==u)
{
op[k].x=u;
op[k++].ch='g';
}
else if(!q.empty()&&q.top()>u)
{
op[k].x=u;
op[k++].ch='i';
q.push(u);
op[k].x=u;
op[k++].ch='g';
}
else{
while(!q.empty()&&q.top()<u)//刪到隊列中最小的數(shù)小于目標數(shù)為止.
{
op[k].x=q.top();
op[k++].ch='r';
q.pop();
}
if(!q.empty()&&q.top()>u || q.empty())
{
op[k].x=u;
op[k++].ch='i';
q.push(u);
}
op[k].x=u;
op[k++].ch='g';
}
}
}
printf("%d\n",k);//總共最少步驟
for(int i=0;i<k;i++)
{
if(op[i].ch=='i')
printf("insert %d\n",op[i].x);
else if(op[i].ch=='r')
printf("removeMin\n");
else
printf("getMin %d\n",op[i].x);
}
}