您的位置:首页 > 其它

PAT-4C-L3-002-堆栈(线段树)

2016-05-17 19:31 429 查看
链接:https://www.patest.cn/contests/gplt/L3-002


L3-002. 堆栈

时间限制

200 ms

内存限制

65536 kB

代码长度限制

8000 B

判题程序

Standard

作者

陈越

大家都知道“堆栈”是一种“先进后出”的线性结构,基本操作有“入栈”(将新元素插入栈顶)和“出栈”(将栈顶元素的值返回并从堆栈中将其删除)。现请你实现一种特殊的堆栈,它多了一种操作叫“查中值”,即返回堆栈中所有元素的中值。对于N个元素,若N是偶数,则中值定义为第N/2个最小元;若N是奇数,则中值定义为第(N+1)/2个最小元。

输入格式:

输入第一行给出正整数N(<= 105)。随后N行,每行给出一个操作指令,为下列3种指令之一:
Push key

Pop

PeekMedian

其中Push表示入栈,key是不超过105的正整数;Pop表示出栈;PeekMedian表示查中值。

输出格式:

对每个入栈指令,将key入栈,并不输出任何信息。对每个出栈或查中值的指令,在一行中打印相应的返回结果。若指令非法,就打印“Invalid”。
输入样例:
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


提交代码

题解:由于区间只有1e5,可以用直接线段树维护下1e5内每个数的个数,然后对于查询直接找到第n/2个就好。

#include <bits/stdc++.h>
using namespace std;
int Scan()
{
int res=0,ch,flag=0;
if((ch=getchar())=='-')flag=1;
else if(ch>='0'&&ch<='9')res=ch-'0';
while((ch=getchar())>='0'&&ch<='9')res=res*10+ch-'0';
return flag?-res:res;
}
void Out(int a)
{
if(a>9)Out(a/10);
putchar(a%10+'0');
}
#define INF 0x3f3f3f3f
#define bug cout<<"bug"<<endl
const int MAXN = 1e5+7;
char str[10];
stack<int> s;
int num[MAXN<<2];
void make_tree(int l, int r, int poi)
{
num[poi]=0;
if(l==r)return;
int mid=(l+r)>>1;
make_tree(l,mid,poi<<1);
make_tree(mid+1,r,poi<<1^1);
}
void update(int l, int r, int poi, int p, int f)
{
if(l==r){num[poi]+=f;return;}
int mid=(l+r)>>1;
if(mid>=p)update(l,mid,poi<<1,p,f);
else update(mid+1,r,poi<<1^1,p,f);
num[poi]=num[poi<<1]+num[poi<<1^1];
}
int find_num(int l, int r, int poi, int p)
{
if(l==r)return l;
int mid=(l+r)>>1;
if(num[poi<<1]>=p)return find_num(l,mid,poi<<1,p);
return find_num(mid+1,r,poi<<1^1,p-num[poi<<1]);
}
int main()
{
int n,p,a;
make_tree(1,MAXN,1);
// bug;
n=Scan();
while(n--)
{
scanf("%s",str);
if(str[1]=='o')
{
if(s.empty()){printf("Invalid\n");continue;}
p=s.top();
printf("%d\n",p);
s.pop();
update(0,MAXN,1,p,-1);
}
else if(str[1]=='u')
{
scanf("%d",&p);
s.push(p);
update(0,MAXN,1,p,1);
}
else if(str[1]=='e')
{
if(s.empty()){printf("Invalid\n");continue;}
int temp=s.size();
if(temp&1)++temp;
printf("%d\n",find_num(0,MAXN,1,temp>>1));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: