解題思路
設總高度為 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
#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";
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。