题目链接: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;
}