置頂

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

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

熱門文章

2026年9月11日 星期五

ZeroJudge 解題筆記:r581.10489 - Boxes of Chocolates

作者:王一哲
日期:2026年9月11日


ZeroJudge 題目連結:r581.10489 - Boxes of Chocolates

解題想法


每筆測資第 $1$ 列只有一個整數 $T$,代表接下來有 $T$ 組測資。第 $2$ 列有兩個整數 $n, b$,分別代表朋友人數、收到的禮物盒數量。接下來 $b$ 列,每列開頭有 $1$ 個數字代表這列的後方有幾個數字,第 $1$ 到倒數第 $2$ 個數字為每一層盒子的數量,最後一個數字為最內層盒子內的巧克力數量。先計算拿到的巧克力總數 $total$,輸出 $total$ 除以 $n$ 的餘數。為了計算每一個盒子內的巧克力數量,可以先設定變數 $t = 1$,接下來依序讀取每層的盒子數量及最內層盒子內的巧克力數量,將 $t$ 乘上這些數字就是這個盒子內的巧克力總數。最後再將所有盒子的巧克力數量相加,對 $n$ 取餘數就是答案。

用 C 或 C++ 解題要很小心,計算盒子內巧克力數量時,每次相加或相乘都要對 $n$ 取餘數,否則數值會超出 int 的上限。

Python 程式碼


使用時間約為 14 ms,記憶體約為 9.5 MB,通過測試。
T = int(input())
for _ in range(T):
    n, b = map(int, input().split())
    total = 0
    for __ in range(b):
        parts = list(map(int, input().split()))
        m = parts[0]
        t = 1
        for i in range(1, m + 1):
            t *= parts[i]
        total += t
    print(total % n)


C++ 程式碼


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

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int T; cin >> T;
    for(int i = 0; i < T; i++) {
        int n, b, total = 0;
        cin >> n >> b;
        for(int j = 0; j < b; j++) {
            int m, t = 1; cin >> m;
            for(int k = 0; k < m; k++) {
                int x; cin >> x;
                t = t * x % n;
            }
            total = (total + t) % n;
        }
        cout << total << "\n";
    }
    return 0;
}


使用時間約為 1 ms,記憶體約為 3.6 MB,通過測試。
#include <cstdio>

int main() {
    int T; scanf("%d", &T);
    for(int i = 0; i < T; i++) {
        int n, b, total = 0;
        scanf("%d %d", &n, &b);
        for(int j = 0; j < b; j++) {
            int m, t = 1;
            scanf("%d", &m);
            for(int k = 0; k < m; k++) {
                int x; scanf("%d", &x);
                t = t * x % n;
            }
            total = (total + t) % n;
        }
        printf("%d\n", total);
    }
    return 0;
}


C 語言程式碼


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

int main() {
    int T; scanf("%d", &T);
    for(int i = 0; i < T; i++) {
        int n, b, total = 0;
        scanf("%d %d", &n, &b);
        for(int j = 0; j < b; j++) {
            int m, t = 1;
            scanf("%d", &m);
            for(int k = 0; k < m; k++) {
                int x; scanf("%d", &x);
                t = t * x % n;
            }
            total = (total + t) % n;
        }
        printf("%d\n", total);
    }
    return 0;
}


沒有留言:

張貼留言