
分析:
考察树状数组 + 二分, 注意以下几点:
1.题目除了正常的进栈和出栈操作外增加了获取中位数的操作, 获取中位数,我们有以下方法:
(1):每次全部退栈,进行排序,太浪费时间,不可取。
(2):题目告诉我们key不会超过10^5,我们可以想到用数组来标记,但不支持快速的统计操作。
(3):然后将数组转为树状数组,可以快速的统计,再配上二分就OK了。
2.二分中我们需要查找的是一点pos,sum(pos)正好是当前个数的一半,而sum(pos - 1)就不满足。
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#include <cctype>
#include <stack>
#include <map> using namespace std; const int Max_required = ; int tree_array[Max_required]; inline int lowbit(int x)
{
return x&(-x);
} void add(int x, int value)
{
while (x < Max_required)
{
tree_array[x] += value;
x += lowbit(x);
}
} int sum(int x)
{
int total = ;
while (x > )
{
total += tree_array[x];
x -= lowbit(x);
}
return total;
} int binary_find(int x)
{
int low = , high = Max_required, mid; while (low <= high)
{
mid = (low + high) >> ;
int total = sum(mid); if (total >= x)
high = mid - ;
else if (total < x)
low = mid + ;
}
return low;
} int main()
{
int n;
stack<int> st;
while (scanf("%d", &n) != EOF)
{
//st.clear();
memset(tree_array, , sizeof(tree_array)); char ch[];
while (n--)
{
scanf("%s", ch);
if (strcmp("Push", ch) == )
{
int pp;
scanf("%d", &pp);
st.push(pp);
add(pp, );
}
else if (strcmp("Pop", ch) == )
{
if (st.empty())
printf("Invalid\n");
else
{
printf("%d\n", st.top());
add(st.top(), -);
st.pop();
}
}
else if (strcmp("PeekMedian", ch) == )
{
int len = st.size();
if (len == ) {
printf("Invalid\n");
continue;
}
int res = -;
if (len % == )
res = binary_find((len + ) / );
else
res = binary_find(len / );
printf("%d\n", res);
}
}
}
return ;
}