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
#include <iostream>
#include <string>
#include <cstring>
#include <stack>
#include <cstdio>
#define MAX 100005
using namespace std;
class BIT{
public:
BIT(int s):Size(s)
{
tree = new int[Size]();
}
~BIT()
{
delete [] tree;
}
void add(int index, int x)
{
while(index <= Size)
{
tree[index] += x;
index += lowbit(index);
}
}
int sum(int index)
{
int tempsum = 0;
while(index)
{
tempsum += tree[index];
index -= lowbit(index);
}
return tempsum;
}
int Find(int pos)//找到一个点比他小的数的数量
{
int left = 1;
int right = MAX;
int mid;
while(left < right)
{
mid = (left+right)/2;
if(sum(mid) >= pos)//大于等于所求目标则中界为右界,这里右界不能等于mid-1,因为mid-1可能是我们所求目标
right = mid;
else
left = mid+1;//否则左界必定大于mid,从mid+1开始,左界不能从mid开始,当因左右界差2且mid+1为目标时,下次循环右界就变成目标了
}
return left;
}
private:
int Size;
int *tree;
int lowbit(int x){return x&(-x);}
};
int main()
{
int n, k;
int temp;
char func[20];
BIT mybit(MAX);
stack<int> mystack;
freopen("in.txt", "r", stdin);
scanf("%d", &n);
getchar();
for(int i=0; i<n; i++)
{
scanf("%s", func);
if(func[1] == 'o')
{
if(mystack.empty())
{
printf("Invalid\n");
}
else{
temp = mystack.top();
printf("%d\n", temp);
mystack.pop();
mybit.add(temp, -1);
}
}
else if(func[1] == 'e')
{
if(mystack.empty())
{
printf("Invalid\n");
}
else
{
k = (mystack.size()+1)/2;
printf("%d\n", mybit.Find(k));
}
}
else if(func[1] == 'u')
{
scanf("%d", &temp);
mystack.push(temp);
mybit.add(temp, 1);
}
}
return 0;
}