2026年10月26日 星期一

ZeroJudge 解題筆記:p923.湯圓 (Tangyuan)

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


ZeroJudge 題目連結:p923.湯圓 (Tangyuan)

題目 pdf 檔連結:湯圓 (Tangyuan)

解題想法


每組測資第一列為一個整數 $n$,代表共有 $n$ 個人;接下來 $n$ 列每列有 $2$ 個數字 $x, y$,分別代表這個人想吃的芝麻和花生湯圓數量。如果湯圓一盒 $10$ 顆,兩種口味的湯圓至少要各買幾盒?各會剩下幾顆?這題可以用兩個變數 $sesame, peanut$,分別代表芝麻、花生湯圓的數量。用一個 for 迴圈讀取每個人要吃的數量並更新 $sesame, peanut$。盒數為數量對 $10$ 取整數除法,如果有餘數再加 $1$ 盒。剩下的數量可以用 $盒數 \times 10 - 要吃的數量$。

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
        sesame, peanut = 0, 0  # 芝麻、花生湯圓數量
        for _ in range(n):
            x = int(data[ptr])
            y = int(data[ptr + 1])
            ptr += 2
            sesame += x
            peanut += y
        
        rem1 = sesame % 10
        num1 = sesame // 10 + (rem1 > 0)
        rem2 = peanut % 10
        num2 = peanut // 10 + (rem2 > 0)
        result.append(f"{num1:d} {10 * num1 - sesame:d}\n{num2:d} {10 * num2 - peanut: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
    
    sesame, peanut = 0, 0  # 芝麻、花生湯圓數量
    for _ in range(n):
        x, y = map(int, input().split())
        sesame += x
        peanut += y
    
    rem1 = sesame % 10
    num1 = sesame // 10 + (rem1 > 0)
    rem2 = peanut % 10
    num2 = peanut // 10 + (rem2 > 0)
    print(f"{num1:d} {10 * num1 - sesame:d}\n{num2:d} {10 * num2 - peanut:d}")


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 sesame = 0, peanut = 0;
        for(int i = 0; i < n; i++) {
            int x, y;
            cin >> x >> y;
            sesame += x;
            peanut += y;
        }
        int rem1 = sesame % 10, rem2 = peanut % 10;  // 芝麻、花生湯圓零頭
        int num1 = sesame / 10 + (rem1 > 0), num2 = peanut / 10 + (rem2 > 0);
        cout << num1 << " " << num1 * 10 - sesame << "\n";
        cout << num2 << " " << num2 * 10 - peanut << "\n";
    }
    return 0;
}


C 語言程式碼


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

int main() {
    int n;
    while(scanf("%d", &n) != EOF) {
        int sesame = 0, peanut = 0;
        for(int i = 0; i < n; i++) {
            int x, y;
            scanf("%d %d", &x, &y);
            sesame += x;
            peanut += y;
        }
        int rem1 = sesame % 10, rem2 = peanut % 10;  // 芝麻、花生湯圓零頭
        int num1 = sesame / 10 + (rem1 > 0), num2 = peanut / 10 + (rem2 > 0);
        printf("%d %d\n", num1, num1 * 10 - sesame);
        printf("%d %d\n", num2, num2 * 10 - peanut);
    }
    return 0;
}


沒有留言:

張貼留言