比较简单的模拟,建议使用STL优先队列。
代码如下:
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; #define N 1000010 char outs[N][20]; int outn[N]; priority_queue<int,vector<int>,greater<int> >que; int main() { int n,num; int tot = 0; while(!que.empty()) que.pop(); char op[20]; scanf("%d",&n); getchar(); while(n--) { scanf("%s",op); if(!strcmp(op,"insert")) { scanf("%d",&num); strcpy(outs[tot],op); outn[tot++] = num; que.push(num); } else if(!strcmp(op,"removeMin")) { if(que.empty()) { strcpy(outs[tot],"insert"); outn[tot++] = 0; que.push(0); } strcpy(outs[tot],op); outn[tot++] = -1; que.pop(); } else if(!strcmp(op,"getMin")) { scanf("%d",&num); bool have = false; while(!que.empty()) { int tmp = que.top(); if(tmp < num) { strcpy(outs[tot],"removeMin"); outn[tot++] = -1; que.pop(); } if(tmp == num) { have = true; break; } if(tmp > num) break; } if(!have) { strcpy(outs[tot],"insert"); outn[tot++] = num; que.push(num); } strcpy(outs[tot],"getMin"); outn[tot++] = num; } } printf("%d\n",tot); for(int i = 0; i < tot; i++) { if(!strcmp(outs[i],"removeMin")) printf("%s\n",outs[i]); else printf("%s %d\n",outs[i],outn[i]); } return 0; }