【題解】ZeroJudge c067: 00591 – Box of Bricks

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=c067

#include <iostream>
using namespace std;

int main() {
    int n, T = 1;
     
    while (cin >> n && n) {
        int sum = 0;
        int a[n];
        for (int i = 0; i < n; i++) {
            cin >> a[i];
            sum += a[i];
        }
        int avg = sum / n;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            if (a[i] > avg)
                ans += a[i] - avg;
        }
        cout << "Set #" << T++ << "\n";
        cout << "The minimum number of moves is " << ans << ".\n\n";
    }
    return 0;
}

Python code (credit: Amy Chou)

iters = 0

while True:
    n = int(input())
    if  n == 0:
        break
    bricks = list(map(int, input().split()))
    avg = sum(bricks) // n
    steps = 0
    for b in bricks:
        if b > avg:
            steps += b - avg
    iters += 1
    print(f"Set #{iters}")
    print(f"The minimum number of moves is {steps}.")
分享本文 Share with friends