a780簡單總量守恆與多餘積木

CPE:Box of Bricks (UVa 591)

只統計高於平均的部分,求最少搬動數。

前往題目練習 →回報教學錯誤每筆時間 O(n),空間 O(n) 儲存高度。

解題思路

設總高度為 S,目標高度必為 S/n。每個高於平均的堆至少要移走 h−S/n 塊,這些必要搬動相加就是答案的下界。低於平均的堆總缺額恰等於總多餘量,因為搬動不改變總積木數。

將每一塊多餘積木直接搬到尚有缺額的堆,每塊只搬一次,就能達到下界。因此不用模擬搬運順序。讀到 n=0 停止;依序印 Set #k、含句點的答案句,且每筆後面保留空白行。

Step-by-step animation

示意:高度 1、2、6

回報動畫錯誤
步驟 1 / 3

求目標

總數 9,三堆的目標高度為 3。

1
2
6
S
9
平均
3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
using namespace std;
int main() {
    int n, tc = 0;
    while (cin >> n && n) {
        vector<int> h(n);
        int sum = 0, moves = 0;
        for (int &x : h) {
            cin >> x;
            sum += x;
        }
        for (int x : h)
            if (x > sum / n)
                moves += x - sum / n;
        cout << "Set #" << ++tc << "\nThe minimum number of moves is " << moves << ".\n\n";
    }
}

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

更多