(天梯赛L3-002)特殊堆栈(vector/树状数组)

题目链接:PTA | 程序设计类实验辅助教学平台

输入样例:

17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop

输出样例:

Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid

 按道理vector插入删除元素的复杂度应该为o(n),如果真是这样的话这道题目我的方法的复杂度就应该被卡了,看了别人的博客也都是这么写的,可能是这道题目数据比较水吧

下面直接进行分析,先说一下vector函数的一个用法

比如说我现在有一个vector p

我要删除下标为k的元素(实际上是第k+1个元素),我可以直接调用函数p.erase(p.begin()+k)

我要在下标为k的元素前加上一个元素t,那么可以直接调用p.insert(p.begin()+k,t)

知道了这些这道题目就很好处理了,我们先用数组模拟一个栈,每次pop或者push直接在上面操作,我们还需要维护一个单调递增的vector用来输出中间值,每次push一个元素我们就对应的在vector中找到他应该在的位置并把他添加进去,而pop一个元素也是对应地找到他的位置直接删除,需要输出中间值直接用vector索引中间值即可

下面是代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>
#include<cmath>
#include<queue>
using namespace std;
const int N=1e5+10;
int st[N],tt;
vector<int>p;
int main()
{
	int n;
	cin>>n;
	char s[15];
	while(n--)
	{
		scanf("%s",s);
		if(s[1]=='u')
		{
			int t;
			scanf("%d",&t);
			st[++tt]=t;
			int id=lower_bound(p.begin(),p.end(),t)-p.begin();
			p.insert(p.begin()+id,t);
		}
		else if(s[1]=='o')
		{
			if(!tt)	puts("Invalid");
			else
			{
				int id=lower_bound(p.begin(),p.end(),st[tt])-p.begin();
				printf("%d\n",st[tt--]);
				p.erase(p.begin()+id);
			}
		}
		else
		{
			if(!tt)	puts("Invalid");
			else printf("%d\n",p[(tt-1)/2]);
		}
	}
	return 0;
}

下面来说一下o(nlogn)的正解:

就是对于中间点的查询我们可以通过线段树或者树状数组来解决,我们每插入一个数就在对应的位置+1,每删除一个数就在对应的位置-1,我们知道当前一共有tt个数,至于找中间值我们只要从前往后二分出来和为(tt+1)/2的位置输出即可,这个公式是综合考虑了奇数和偶数的情况

下面是代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
const int N=1e5+10;
int st[N],tt;
int d[N];
int lowbit(int x)
{
	return x&-x;
}
void add(int pos,int val)
{
	for(int i=pos;i<N;i+=lowbit(i))
		d[i]+=val;
}
int query(int pos)
{
	int ans=0;
	for(int i=pos;i;i-=lowbit(i))
		ans+=d[i];
	return ans;
}
int main()
{
	int n;
	cin>>n;
	char s[15];
	while(n--)
	{
		scanf("%s",s);
		if(s[1]=='u')
		{
			int t;
			scanf("%d",&t);
			st[++tt]=t;
			add(st[tt],1);
		}
		else if(s[1]=='o')
		{
			if(!tt)	puts("Invalid");
			else
			{
				add(st[tt],-1);
				printf("%d\n",st[tt--]);
			}
		}
		else
		{
			if(!tt)	puts("Invalid");
			else
			{
				int l=1,r=N-1;
				while(l<r)//二分中间位置
				{
					int mid=l+r>>1;
					if(query(mid)>=(tt+1)/2) r=mid;
					else l=mid+1;
				}
				printf("%d\n",l);
			}
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值