熱門文章

2025年11月17日 星期一

ZeroJudge 解題筆記:i213. stack 練習

作者:王一哲
日期:2025年11月17日


ZeroJudge 題目連結:i213. stack 練習

解題想法


這題是堆疊 (stack) 的基本操作,在 Python 可以用 list 代替,在 C++ 可以用 stack 或 vector。

Python 程式碼


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


C++ 程式碼


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

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

使用時間約為 5 ms,記憶體約為 484 kB,通過測試。

#include <cstdio>
#include <vector>
using namespace std;

int main() {
    int n; scanf("%d", &n);
    vector<int> st;
    for(int i=0; i<n; i++) {
        int k; scanf("%d", &k);
        if (k == 1) {
            int val; scanf("%d", &val);
            st.push_back(val);
        } else if (k == 2) {
            if (!st.empty()) printf("%d\n", st.back());
            else printf("-1\n");
        } else if (k == 3) {
            if (!st.empty()) st.pop_back();
        }
    }
    return 0;
}


沒有留言:

張貼留言