解題思路
把美元字串拆成整數美分,總和為 S,平均下界 lo=S//n,上界 hi=ceil(S/n)。每人的最終負擔可設為 lo 或 hi,其中 S%n 人負擔 hi,其餘負擔 lo。原本付不到 lo 的人,至少還須支付 need=sum(max(0,lo−x));原本付超過 hi 的人,至少應獲補償 give=sum(max(0,x−hi))。金錢由少付者轉給多付者,讓少付者的負擔增加、多付者的負擔減少。
最少移轉是 max(need,give)。因為兩者都是必要下界,而將較高目標 hi 優先給原本花費較多者,即可在不增加往返轉交的情況下達到較大的下界。若直接把平均四捨五入,可能多收或少收幾美分。讀 n=0 結束,以 $ 加兩位小數輸出。
Step-by-step animation
示意:15.00、15.01、3.00、3.01 美元
步驟 1 / 3
美分總和
四人合計 3602 美分。
1500
1501
300
301
- S
- 3602
- n
- 4
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
#include <algorithm>
using namespace std;
int main() {
int n;
while (cin >> n && n) {
vector<long long> a(n);
long long sum = 0;
for (auto &x : a) {
string s;
cin >> s;
auto p = s.find('.');
x = stoll(s.substr(0, p)) * 100 + stoll(s.substr(p + 1));
sum += x;
}
long long lo = sum / n, hi = (sum + n - 1) / n, need = 0, give = 0;
for (auto x : a) {
need += max(0LL, lo - x);
give += max(0LL, x - hi);
}
long long answer = max(need, give);
cout << '$' << answer / 100 << '.' << setw(2) << setfill('0') << answer % 100 << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。