pat 甲级 1057 Stack(30) (树状数组+二分)

本文介绍了一个特殊的栈数据结构实现,除了基本的push和pop操作外,还支持peekMedian操作,用于返回栈中所有元素的中位数。通过使用线段树和二分查找,文章详细阐述了如何高效地进行中位数查询,即使在频繁的插入和删除操作下也能保持良好的性能。

1057 Stack (30 分)

Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian -- return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if Nis odd.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤10​5​​). Then N lines follow, each contains a command in one of the following 3 formats:

Push key
Pop
PeekMedian

where key is a positive integer no more than 10​5​​.

Output Specification:

For each Push command, insert key into the stack and output nothing. For each Pop or PeekMedian command, print in a line the corresponding returned value. If the command is invalid, print Invalidinstead.

Sample Input:

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

Sample Output:

Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int st[100005];
ll bit[1000005];
ll n;
void add(ll i,ll x)
{
    while(i<=n)
    {
        bit[i]+=x;
        i+=i&-i;
    }
}
ll sum(ll i)
{
    ll s=0;
    while(i>0)
    {
        s+=bit[i];
        i-=i&-i;
    }
    return s;
}
int pos=0;
int main()
{
    n=100000;
    //freopen("in.txt","r",stdin);
    int N;
    cin>>N;
    string op;
    while(N--)
    {
        cin>>op;
        if(op[1]=='o')
        {
            if(pos==0){cout<<"Invalid"<<endl;continue;}
            cout<<st[pos]<<endl;
            add(st[pos],-1);
            pos--;
        }
        else if(op[1]=='u')
        {
            int num;
            cin>>num;
            add(num,1);
            st[++pos]=num;
        }
        else if(op[1]=='e')
        {
            if(pos==0){cout<<"Invalid"<<endl;continue;}
            int x=(pos%2==0)?pos/2:(pos+1)/2;
            int lb=0;int ub=100001;
            while(ub-lb>1)
            {
                int mid=(ub+lb)/2;
                if(sum(mid)<x)lb=mid;
                else ub=mid;
            }
            cout<<ub<<endl;
        }
        else {
            cout<<"Invalid"<<endl;continue;
        }
    }
    return 0;
}





 

### 如何使用栈存储字符数组 在 C 和 C++ 中,可以利用栈来存储字符数组。由于栈是一种后进先出(LIFO)的数据结构,在实现上通常通过动态分配内存或者固定大小的数组来模拟栈的行为。 以下是基于引用内容以及专业知识构建的一种方法: #### 使用栈存储字符数组的核心概念 1. **栈的特点** 栈具有固定的容量,并且遵循 LIFO 的操作原则。当向栈中压入数据时,如果超出栈的最大容量,则会发生溢出错误[^3]。 2. **字符数组的特性** 字符数组本质上是一个连续的内存空间,用于存储一系列字符。在 C 或者 C++ 中,字符数组既可以存放在栈中也可以存放在堆中[^4]。 --- #### 实现方案 下面展示一种简单的实现方式,其中定义了一个栈类 `CharStack` 来管理字符数组的操作。 ```cpp #include <iostream> #include <cstring> class CharStack { private: char* data; // 动态分配的字符数组 int capacity; // 栈的最大容量 int topIndex; // 当前栈顶的位置 public: // 构造函数:初始化栈并设置最大容量 CharStack(int size) : capacity(size), topIndex(-1) { data = new char[capacity]; } // 析构函数:释放动态分配的内存 ~CharStack() { delete[] data; } // 压入字符到栈中 bool push(char c) { if (topIndex >= capacity - 1) { std::cout << "Error: Stack Overflow!" << std::endl; return false; } data[++topIndex] = c; return true; } // 弹出栈顶字符 char pop() { if (isEmpty()) { std::cout << "Error: Stack Underflow!" << std::endl; return '\0'; } return data[topIndex--]; } // 查看栈顶字符而不弹出 char peek() const { if (isEmpty()) { std::cout << "Error: Stack is empty!" << std::endl; return '\0'; } return data[topIndex]; } // 判断栈是否为空 bool isEmpty() const { return topIndex == -1; } // 打印当前栈的内容 void display() const { if (isEmpty()) { std::cout << "Stack is empty." << std::endl; return; } for (int i = 0; i <= topIndex; ++i) { std::cout << data[i] << ' '; } std::cout << std::endl; } }; // 测试代码 int main() { CharStack stack(10); // 定义一个容量为10的栈 // 向栈中压入一些字符 stack.push('H'); stack.push('e'); stack.push('l'); stack.push('l'); stack.push('o'); // 显示栈中的内容 std::cout << "Current stack content:" << std::endl; stack.display(); // 弹出栈顶字符并显示 std::cout << "Popped character: " << stack.pop() << std::endl; // 再次查看栈顶字符 std::cout << "Top of the stack after popping: " << stack.peek() << std::endl; return 0; } ``` --- #### 关键点解析 1. **动态内存分配** 在上述代码中,`data` 是一个指向字符类型的指针,通过 `new` 运算符为其分配了一块指定大小的内存区域。这种方式使得我们可以灵活控制栈的大小。 2. **边界条件处理** 需要特别注意的是,当尝试向已满的栈中压入新元素时,应抛出异常或返回错误提示;同样地,从空栈中弹出元素也会引发类似的错误情况。 3. **性能分析** 对于单个字符的插入和删除操作而言,时间复杂度均为 \(O(1)\),因为这些动作仅涉及更新少量变量值即可完成[^2]。 --- #### 总结 以上展示了如何借助自定义的 `CharStack` 类型对象来实现对字符数组的有效管理和操作过程。这种方法不仅能够满足基本需求,还具备一定的扩展性和鲁棒性。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值