置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

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;
}


沒有留言:

張貼留言