模拟 + 排序 - 特殊堆栈 - L3-002
注意:
本题取中值并非取栈中间的值,而是指值大小的中位数。
分析:
本题共有三种操作:增、删、查。
因为我们要快速查询当前所有元素的中位数,我们希望这个列表是有序的,这样我们可以二分。
于是最暴力的想法:开两个数组,一个模拟栈,另一个维护有序表,每次增、删操作就维护一下有序表。
有序表可以用vector来模拟,方便使用它的插入insert
和删除erase
函数。
理论上时间复杂度是超了的,但是也过了(天梯赛数据还是挺友好的)。
最后在注意一下有序表的下标。
erase
函数
iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);
insert
函数
//single element (1)
iterator insert (const_iterator position, const value_type& val);
代码:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<vector>
using namespace std;
const int N = 100010;
int n, x;
char op[20];
int stk[N], top;
vector<int> od_list;
int main()
{
scanf("%d", &n);
while(n --)
{
scanf("%s", op);
if(!strcmp(op, "Pop"))
{
if(top == 0)
{
puts("Invalid");
continue;
}
else
{
auto it = lower_bound(od_list.begin(), od_list.end(), stk[top]);
od_list.erase(it);
printf("%d\n", stk[top --]);
}
}
else if(!strcmp(op, "PeekMedian"))
{
if(top & 1) printf("%d\n", od_list[top / 2]);
else
{
if(top / 2 > 0) printf("%d\n", od_list[top / 2 - 1]);
else puts("Invalid");
}
}
else
{
scanf("%d", &x);
stk[++ top] = x;
auto it = lower_bound(od_list.begin(), od_list.end(), x);
od_list.insert(it, x);
}
}
return 0;
}