Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian -- return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<= 105). Then N lines follow, each contains a command in one of the following 3 formats:
Push keyPop
PeekMedian
where key is a positive integer no more than 105.
Output Specification:
For each Push command, insert key into the stack and output nothing. For each Pop or PeekMedian command, print in a line the corresponding returned value. If the command is invalid, print "Invalid" instead.
Sample Input:17 Pop PeekMedian Push 3 PeekMedian Push 2 PeekMedian Push 1 PeekMedian Pop Pop Push 5 Push 4 PeekMedian Pop Pop Pop PopSample Output:
Invalid Invalid 3 2 2 1 2 4 4 5 3 Invalid
//1057 by Binary Index Tree
//see the following blog to understand Binary Index Tree
//http://blog.csdn.net/int64ago/article/details/7429868
#include<iostream>
#include<vector>
using namespace std;
#define max 100001
int bit[max];//binary index tree
vector<int>st;//the stack
int lowbit(int k)
{
return k&(-k);
}
void add(int index,int value)
{//if a value is added or deleted in the stack, update the binary index tree
while(index<max)
{
bit[index] += value;
index += lowbit(index);
}
}
int sum(int index)
{//calculate how many value which is smaller than index in the current stack
int sum=0;
while(index>0)
{
sum += bit[index];
index -= lowbit(index);
}
return sum;
}
int binarysearch()
{//search the value of the median
int pos=(st.size()+1)/2;//position of the median if stack is sorted
int down=0,up=max-1;
while(up>down)
{
int mid=(up+down)/2;
if(sum(mid)>=pos)
up=mid;
else
down=mid+1;
}
return down;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;++i)
{
char in[15];
scanf("%s",in);
if(in[1]=='u')
{//Push
int t;
scanf("%d",&t);
st.push_back(t);
add(t,1);//update the binary index tree
}
else if(in[1]=='o')
{//Pop
if(st.empty())
printf("Invalid\n");
else
{
printf("%d\n",st[st.size()-1]);
add(st[st.size()-1],-1);//update the binary index tree
st.pop_back();
}
}
else
{//PeekMedian
if(st.empty())
printf("Invalid\n");
else
{
int temp;
temp=binarysearch();
printf("%d\n",temp);
}
}
}
return 0;
}