1 条题解

  • 0
    @ 2026-8-19 9:50:32

    题解

    用 stack<long long> 直接模拟。

    • push(x) 入栈;
    • pop() 删除栈顶,但操作前必须判断是否为空;
    • top() 查询栈顶;
    • size() 得到大小。

    时间复杂度 O(q)O(q)。

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    
        int q;
        cin >> q;
        stack<long long> s;
    
        while (q--) {
            int op;
            cin >> op;
            if (op == 1) {
                long long x;
                cin >> x;
                s.push(x);
            } else if (op == 2) {
                if (s.empty()) cout << "Empty\n";
                else s.pop();
            } else if (op == 3) {
                if (s.empty()) cout << "Empty\n";
                else cout << s.top() << '\n';
            } else {
                cout << s.size() << '\n';
            }
        }
        return 0;
    }
    
    • 1

    信息

    ID
    5156
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    1
    已通过
    1
    上传者