ACM天梯赛 L3-02 堆栈(线段树)

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
思路:用线段树来维护区间内各个数出现的总次数
代码如下:看了就能理解。
//https://www.patest.cn/contests/gplt/L3-002
//L3-002. 堆栈
#include<stack>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=100005;
const int last=100000;
int sum[maxn*4];
stack<int>stk;
void update(int l,int r,int pos,int end,int flag)
{
  if(l==r)
  {
    sum[pos]+=flag;
    return;
  }
  int mid=(l+r)>>1;
  if(end<=mid)update(l,mid,pos<<1,end,flag);
  else update(mid+1,r,pos<<1|1,end,flag);
  sum[pos]=sum[pos<<1]+sum[pos<<1|1];
}
void query(int l,int r,int pos,int x)//x表示在这个区间里面的第几个数 
{
  if(l==r){printf("%d\n",l);return;}
  int mid=(l+r)>>1;
  if(x<=sum[pos<<1])  query(l,mid,pos<<1,x);
  else query(mid+1,r,pos<<1|1,x-sum[pos<<1]);
}
int main()
{
  int n,key,count=0;
  char q[10];
  scanf("%d",&n);
  while(n--)
  {
    scanf("%s",q);
    if(q[1]=='u')
    {
      scanf("%d",&key);
      update(1,last,1,key,1);
      stk.push(key);
      count++;
    }
    else if(q[1]=='o')
    {
      if(!count)printf("Invalid\n");
      else 
      {
        key=stk.top();
        stk.pop();
        update(1,last,1,key,-1);
        count--;
        printf("%d\n",key);
      }
    }
    else
    {
      //int x=(count+1)/2;//要查询的数的位置 
      if(!count)printf("Invalid\n");
      else query(1,last,1,(count+1)>>1);
    }
  }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值