L3-002. 堆栈
时间限制
200 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
大家都知道“堆栈”是一种“先进后出”的线性结构,基本操作有“入栈”(将新元素插入栈顶)和“出栈”(将栈顶元素的值返回并从堆栈中将其删除)。现请你实现一种特殊的堆栈,它多了一种操作叫“查中值”,即返回堆栈中所有元素的中值。对于N个元素,若N是偶数,则中值定义为第N/2个最小元;若N是奇数,则中值定义为第(N+1)/2个最小元。
输入格式:
输入第一行给出正整数N(<= 105)。随后N行,每行给出一个操作指令,为下列3种指令之一:
Push keyPop
PeekMedian
其中Push表示入栈,key是不超过105的正整数;Pop表示出栈;PeekMedian表示查中值。
输出格式:
对每个入栈指令,将key入栈,并不输出任何信息。对每个出栈或查中值的指令,在一行中打印相应的返回结果。若指令非法,就打印“Invalid”。
输入样例:17 Pop PeekMedian Push 3 PeekMedian Push 2 PeekMedian Push 1 PeekMedian Pop Pop Push 5 Push 4 PeekMedian Pop Pop Pop Pop输出样例:
Invalid Invalid 3 2 2 1 2 4 4 5 3 Invalid
思路:用线段树来维护区间内各个数出现的总次数
代码如下:看了就能理解。
//https://www.patest.cn/contests/gplt/L3-002 //L3-002. 堆栈
#include<stack> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int maxn=100005; const int last=100000; int sum[maxn*4]; stack<int>stk; void update(int l,int r,int pos,int end,int flag) { if(l==r) { sum[pos]+=flag; return; } int mid=(l+r)>>1; if(end<=mid)update(l,mid,pos<<1,end,flag); else update(mid+1,r,pos<<1|1,end,flag); sum[pos]=sum[pos<<1]+sum[pos<<1|1]; } void query(int l,int r,int pos,int x)//x表示在这个区间里面的第几个数 { if(l==r){printf("%d\n",l);return;} int mid=(l+r)>>1; if(x<=sum[pos<<1]) query(l,mid,pos<<1,x); else query(mid+1,r,pos<<1|1,x-sum[pos<<1]); } int main() { int n,key,count=0; char q[10]; scanf("%d",&n); while(n--) { scanf("%s",q); if(q[1]=='u') { scanf("%d",&key); update(1,last,1,key,1); stk.push(key); count++; } else if(q[1]=='o') { if(!count)printf("Invalid\n"); else { key=stk.top(); stk.pop(); update(1,last,1,key,-1); count--; printf("%d\n",key); } } else { //int x=(count+1)/2;//要查询的数的位置 if(!count)printf("Invalid\n"); else query(1,last,1,(count+1)>>1); } } }