Codeforces 681C:Heap Operations
Heap Operations
題目鏈接:
http://codeforces.com/contest/681/problem/C
題意:
有個堆,有三種操作
- insert?x?— 把x加到堆里
- getMin?x?— 得到堆里的最小值,且最小值等于x ? ? 當堆為空或者最小值不等于x時操作違法
- removeMin?— 刪除堆里的最小值 ? ? ? ? ? ? ? ? ? ? ? 當堆為空時操作違法
?題目給出了一些操作,不一定合法,往里再添加一些操作使得所有的操作都合法,求添加操作最少的情況并按序輸出全部操作(新添加的和已存在的)
題解:
優先隊列模擬操作
當前操作為insert x時向隊列中加入x
當前操作為removeMin時將隊列的top()刪除,若隊列為空則在removeMin前先insert一個在x的定義域內的任意值就好了
當前操作為getMin x時:如果隊列為空,則先insert x
如果隊列不為空,則比較隊列的top()和x的大小關系,只要top()小于x就一直removeMin,在此之后若top()大于x或隊列為空,則insert x
代碼
#include<stdio.h>
#include<map>
#include<queue>
using namespace std;
struct Node
{
char ss;
int x;
}t[1000005];
char s[20];
struct node
{
int x;
node(int a=0)
{
x=a;
}
bool friend operator<(node a,node b)
{
return a.x>b.x;
}
};
priority_queue<node>w;
int main()
{
int n,x,num=0;
while(!w.empty())w.pop();
scanf("%d",&n);
for(int i=1;i<=n;++i)
{
scanf("%s",s);
if(s[0]=='i')
{
scanf("%d",&x);
t[num].ss='i';
t[num++].x=x;
w.push(node(x));
}
else if(s[0]=='g')
{
scanf("%d",&x);
while(!w.empty())
{
if(w.top().x<x)
{
t[num++].ss='r';
w.pop();
}
else break;
}
if(w.empty()||w.top().x!=x)
{
t[num].ss='i';
t[num++].x=x;
w.push(node(x));
}
t[num].ss='g';
t[num++].x=x;
}
else
{
if(!w.empty())
{
t[num++].ss='r';
w.pop();
}
else
{
t[num].ss='i';
t[num++].x=1;
t[num++].ss='r';
}
}
}
printf("%d\n",num);
for(int i=0;i<num;++i)
if(t[i].ss=='r')
printf("removeMin\n");
else if(t[i].ss=='g')printf("getMin %d\n",t[i].x);
else printf("insert %d\n",t[i].x);
}
轉載于:https://www.cnblogs.com/kiuhghcsc/p/5596790.html
總結
以上是生活随笔為你收集整理的Codeforces 681C:Heap Operations的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hive Shell 常用命令
- 下一篇: EZ的间谍网络(codevs 4093)