a086簡單讀題、輸入與基本計算

TOI 2026/03 新手組:湯圓

分別加總芝麻與花生湯圓的需求,算出最少購買盒數與剩餘顆數。

前往題目練習 →回報教學錯誤時間 O(N) ・ 額外空間 O(1)

這題在學什麼

先讀入參加人數 N,將接下來 N 人的芝麻需求 Xi 與花生需求 Yi 分別累加為 sesame 和 peanut。兩種口味不能混裝,所以要各自計算;也不是替每個人分別買整盒。

若某種口味總共需要 total 顆,買 boxes 盒就有 10 × boxes 顆,必須滿足 10 × boxes ≥ total。為了買最少盒,取 boxes = ⌈total / 10⌉;對非負整數可寫成 (total + 9) / 10,Python 則用 (total + 9) // 10。

剩餘顆數是 boxes × 10 − total,不是 total % 10:例如需要 13 顆,買 2 盒後剩下 20 − 13 = 7 顆。需求恰好整盒時剩 0 顆;需求為 0 時公式也會得到 0 盒、0 顆,不需要另外多買一盒。

題目範例的芝麻需求為 3 + 0 + 8 + 2 = 13,花生需求為 7 + 2 + 0 + 5 = 14,因此依序輸出 2 7 與 2 6,各占一行。最多 50 人、每人每種口味最多 50 顆,總需求最多 2500 顆,C++ 的 int 足以儲存。

Step-by-step animation

湯圓需求、購買盒數與剩餘顆數

回報動畫錯誤
步驟 1 / 6

讀入 N 與第 1 人

N = 4。兩個總和先設為 0,再加入第 1 人的芝麻 3 顆、花生 7 顆。

第 1 人:3、7
芝麻總計 3
花生總計 7
已讀人數
1
芝麻需求
3
花生需求
7

Reference solution

回報程式錯誤

完整程式

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int sesame = 0, peanut = 0;
    for (int i = 0; i < n; ++i) {
        int x, y;
        cin >> x >> y;
        sesame += x;
        peanut += y;
    }

    int sesameBoxes = (sesame + 9) / 10;
    int peanutBoxes = (peanut + 9) / 10;
    cout << sesameBoxes << ' ' << sesameBoxes * 10 - sesame << '\n';
    cout << peanutBoxes << ' ' << peanutBoxes * 10 - peanut << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多