首页 > 其他分享 >7-3 特殊堆栈

7-3 特殊堆栈

时间:2022-11-04 15:36:24浏览次数:41  
标签:begin 特殊 PeekMedian int Pop Push 堆栈

堆栈是一种经典的后进先出的线性结构,相关的操作主要有“入栈”(在堆栈顶插入一个元素)和“出栈”(将栈顶元素返回并从堆栈中删除)。本题要求你实现另一个附加的操作:“取中值”——即返回所有堆栈中元素键值的中值。给定 N 个元素,如果 N 是偶数,则中值定义为第 N/2 小元;若是奇数,则为第 (N+1)/2 小元。

输入格式:
输入的第一行是正整数 N(≤10 ^5 )。随后 N 行,每行给出一句指令,为以下 3 种之一:

Push key
Pop
PeekMedian

其中 key 是不超过 10^5的正整数;Push 表示“入栈”;Pop 表示“出栈”;PeekMedian 表示“取中值”。

输出格式:
对每个 Push 操作,将 key 插入堆栈,无需输出;对每个 Pop 或 PeekMedian 操作,在一行中输出相应的返回值。若操作非法,则对应输出 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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB

解题代码:

#include<bits/stdc++.h>
using namespace std;
int a[100005],top;
vector<int> v;
void Insert(int x)
{
    int no=lower_bound(v.begin(),v.end(),x)-v.begin();
    v.insert(v.begin()+no,x);
}
void Delete(int x)
{
    int no=lower_bound(v.begin(),v.end(),x)-v.begin();
    v.erase(v.begin()+no);
}
int Query()
{
    int len=v.size();
    if(len%2==0)
        return v[len/2-1];
    else
        return v[(len+1)/2-1];
}
int main()
{
    int n,x;
    string s;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>s;
        if(s=="Pop")
        {
            if(top==0)
                cout<<"Invalid"<<endl;
            else
            {
                cout<<a[top-1]<<endl;
                Delete(a[top-1]);
                top--;
            }
        }
        else if(s=="Push")
        {
            cin>>x;
            a[top++]=x;
            Insert(x);
        }
        else
        {
            if(top==0)
            {
                cout<<"Invalid"<<endl;
                continue;
            }
            cout<<Query()<<endl;
        }
    }
    return 0;
}

标签:begin,特殊,PeekMedian,int,Pop,Push,堆栈
From: https://www.cnblogs.com/link-way/p/16857948.html

相关文章