熱門文章

2026年5月8日 星期五

ZeroJudge 解題筆記:b923. stack 堆疊的模板題

作者:王一哲
日期:2026年5月8日


ZeroJudge 題目連結:b923. stack 堆疊的模板題

解題想法


單純的 stack 操作,在 Python 解題可以直接用 list 模擬 stack,在 C++ 建議引入 stack 或 deque 函式庫。

Python 程式碼


使用時間約為 18 ms,記憶體約為 8.4 MB,通過測試。
st = []
n = int(input())
for _ in range(n):
    line = input().split()
    if line[0] == '1':
        if st: st.pop()
    elif line[0] == '2':
        if st: print(st[-1])
    elif line[0] == '3':
        st.append(int(line[1]))


C++ 程式碼


使用時間約為 1 ms,記憶體約為 3 MB,通過測試。
#include <cstdio>
#include <stack>
using namespace std;

int main() {
    stack<int> st;
    int n, op, x;
    scanf("%d", &n);
    for(int i=0; i<n; i++) {
        scanf("%d", &op);
        if (op == 1) {
            if (!st.empty()) st.pop();
        } else if (op == 2) {
            if (!st.empty()) printf("%d\n", st.top());
        } else if (op == 3) {
            scanf("%d", &x);
            st.push(x);
        }
    }
    return 0;
}

使用時間約為 1 ms,記憶體約為 3 MB,通過測試。
#include <cstdio>
#include <deque>
using namespace std;

int main() {
    deque<int> dq;
    int n, op, x;
    scanf("%d", &n);
    for(int i=0; i<n; i++) {
        scanf("%d", &op);
        if (op == 1) {
            if (!dq.empty()) dq.pop_back();
        } else if (op == 2) {
            if (!dq.empty()) printf("%d\n", dq.back());
        } else if (op == 3) {
            scanf("%d", &x);
            dq.push_back(x);
        }
    }
    return 0;
}


沒有留言:

張貼留言