1057. Stack (30)
思路:桶+哈希
注意,可能存在一样的key值(最后两个测试点),记录和查询中位数时要注意处理。
#include <stdio.h>
int table[320][320];
int count[320];
int stack[320*320],top=0;
void push(int e){
stack[top++]=e;
table[e/320][e%320]++;
count[e/320]++;
}
void pop(void){
if(top==0)
printf("Invalid\n");
else{
int e=stack[--top];
printf("%d\n",e);
table[e/320][e%320]--;
count[e/320]--;
}
}
void peekmedian(void)
{
if(top==0)
printf("Invalid\n");
else
{
int k=(top+1)/2,i,c=0;
for(i=0;i<320;++i){
if(c+count[i]>=k)break;
c+=count[i];
}
for(int j=0;j<320;++j){
c+=table[i][j];
if(c>=k){
printf("%d\n",i*320+j);break;
}
}
}
}
int main(){
int n,e;
char s[12];
scanf("%d",&n);
while(n--){
scanf("%s",s);
switch(s[1]){
case 'u':{scanf("%d",&e);push(e);};break;
case 'o':pop();break;
case 'e':peekmedian();break;
}
}
return 0;
}