模拟 + 排序 - 特殊堆栈 - L3-002

模拟 + 排序 - 特殊堆栈 - 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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值