解題思路
掃描 n 個數,維護總和、最大值、最小值。平均取 |總和|×100 除以 n 得到百分之一單位的商 q 與餘數 r;若 2r≥n,就把 q 加一。
最後恢復正負號,輸出 q//100 與補足兩位的 q%100。這是先對絕對值四捨五入再恢復符號,避免二進位浮點誤差,負數恰半時也會遠離零。總和為負但四捨五入為零時不輸出負零。
O(nL) 大整數運算時間,示範儲存輸入 O(nL),L 為整數位數。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。
Step-by-step animation
教學示意(以步驟描述中的輸入為準)
步驟 1 / 3
示意數列
−1、0、0,總和為 −1。
-1
0
0
- 總和
- −1
- n
- 3
#include <bits/stdc++.h>
using namespace std;
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
int main() {
int n;
cin >> n;
cpp_int s = 0, mn, mx;
for (int i = 0; i < n; i++) {
cpp_int x;
cin >> x;
s += x;
if (!i || x < mn)
mn = x;
if (!i || x > mx)
mx = x;
}
bool neg = s < 0;
if (neg)
s = -s;
cpp_int z = s * 100, q = z / n, r = z % n;
if (2 * r >= n)
q++;
int tail = (q % 100).convert_to<int>();
if (neg && q != 0)
cout << '-';
cout << q / 100 << '.' << setw(2) << setfill('0') << tail << '\n'
<< mx << '\n'
<< mn << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。