置頂

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

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

熱門文章

2026年10月24日 星期六

ZeroJudge 解題筆記:p921.紅包 (Red Envelope)

作者:王一哲
日期:2026年10月24日


ZeroJudge 題目連結:p921.紅包 (Red Envelope)

題目 pdf 檔連結:紅包 (Red Envelope)

解題想法


每組測資第一列為一個整數 $n$,代表共有 $n$ 個紅包;接下來 $n$ 列每列有 $3$ 個數字,分別代表 100、500 和 1000 元的鈔票數量;計算這 $n$ 個紅包的總金額。這題可以用 $3$ 個變數或是一個長度 $3$ 的陣列記錄 $3$ 種鈔票的數量,最後再印出數量乘以面額的加總。

Python 程式碼


使用時間約為 14 ms,記憶體約為 9.6 MB,通過測試。
def solve():
    import sys

    result = []
    data = sys.stdin.read().split()
    ptr = 0
    while ptr < len(data):
        n = int(data[ptr])
        ptr += 1
        cnt = [0, 0, 0]# 100, 500, 1000 總張數
        for _ in range(n):
            a, b, c = map(int, data[ptr : ptr + 3])  # 100, 500, 1000 張數
            ptr += 3
            cnt[0] += a
            cnt[1] += b
            cnt[2] += c
        result.append(f"{cnt[0] * 100 + cnt[1] * 500 + cnt[2] * 1000:d}\n")
    sys.stdout.write("".join(result))

if __name__ == "__main__":
    solve()


使用時間約為 14 ms,記憶體約為 9.6 MB,通過測試。
while True:
    try:
        n = int(input())
    except EOFError:
        break
    
    cnt = [0, 0, 0]  # 100, 500, 1000 總張數
    for _ in range(n):
        a, b, c = map(int, input().split())  # 100, 500, 1000 張數
        cnt[0] += a
        cnt[1] += b
        cnt[2] += c
    print(cnt[0] * 100 + cnt[1] * 500 + cnt[2] * 1000)


C++ 程式碼


使用時間約為 2 ms,記憶體約為 3.5 MB,通過測試。
#include <iostream>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int n;
    while(cin >> n) {
        // 讀取測資
        int cnt[3] = {0};  // 100, 500, 1000 總張數
        for(int i = 0; i < n; i++) {
            int a, b, c;
            cin >> a >> b >> c;
            cnt[0] += a;
            cnt[1] += b;
            cnt[2] += c;
        }
        cout << cnt[0] * 100 + cnt[1] * 500 + cnt[2] * 1000 << "\n";
    }
    return 0;
}


C 語言程式碼


使用時間約為 1 ms,記憶體約為 1.6 MB,通過測試。
#include <stdio.h>

int main() {
    int n;
    while(scanf("%d", &n) != EOF) {
        // 讀取測資
        int cnt[3] = {0};  // 100, 500, 1000 總張數
        for(int i = 0; i < n; i++) {
            int a, b, c;
            scanf("%d %d %d", &a, &b, &c);
            cnt[0] += a;
            cnt[1] += b;
            cnt[2] += c;
        }
        printf("%d\n", cnt[0] * 100 + cnt[1] * 500 + cnt[2] * 1000);
    }
    return 0;
}


沒有留言:

張貼留言