B3614 【模板】栈 c++ 题解

这道模板题主要为栈的基本操作,栈是一种先进后出的数据存储结构,STL栈的主要函数如下:

stack<数据类型> s

s.pop()弹出栈顶元素

s.top()访问栈顶元素

s.push(x)将x压入栈中

s.empty()判断栈是否为空

s.size()取栈的长度

注意:空栈操作:在栈为空时调用 top()pop() 会导致未定义行为,操作前务必用 empty() 判断

需引用#include<stack>

那么,这道题就很简单了

代码如下:

点击查看代码
#include<bits/stdc++.h>
using namespace std;
int main(){
    int T;
    cin>>T;
    while(T--){
        unsigned long long n;
        cin>>n;
        stack<unsigned long long>stc;
        while(n--){
            string s;
            cin>>s;
            if(s=="push"){
                unsigned long long x;
                cin>>x;
                stc.push(x);
            }
            else if(s=="query"){
                if(stc.empty()){
                    cout<<"Anguei!"<<"\n";
                }
                else cout<<stc.top()<<"\n";
            }
            else if(s=="size"){
                cout<<stc.size()<<"\n";
            }
            else if(s=="pop"){
                if(stc.empty()){
                    cout<<"Empty"<<"\n";
                }
                else{
                    stc.pop();
                }
            }
        }
    }
    return 0;
}

需要注意的是,这道题的数据范围非常大,要用unsigned long long,并且要关闭同步流,否则会TLE,而且此题有多测,栈需要清空

posted @ 2026-09-10 10:21  JYJ20141211  阅读(8)  评论(0)    收藏  举报