解題思路
排序整數並求平均與母體標準差。
以大整數求S=sum x與T=sum x²。平均為S/n,母體變異數可改寫為(nT−S²)/n²,完全避開大量浮點相減。
平均用精確有理數half-up。標準差縮放100後,先求k=floor sqrt(10000(nT−S²)/n²)。
比較4×10000(nT−S²)與n²(2k+1)²即可精確判斷是否應向上捨入,包括恰半;排序後的原整數保留重複。
時間 O(n log n)次整數比較及O(n)次大整數運算,空間 O(n);另加大整數平方根成本。
Step-by-step animation
整數1與3的平均及母體標準差
步驟 1 / 3
步驟 1
示例1、3,排序仍1、3。
S=4
T=10
n=2
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
#include <boost/rational.hpp>
using Q = boost::rational<cpp_int>;
Q rat(cpp_int a, cpp_int b) {
if (b < 0) {
a = -a;
b = -b;
}
return Q(a, b);
}
cpp_int abig(cpp_int a) {
return a < 0 ? -a : a;
}
cpp_int ten(int n) {
cpp_int a = 1;
while (n--)
a *= 10;
return a;
}
Q dec(string s) {
auto slash = s.find('/');
if (slash != string::npos)
return Q(cpp_int(s.substr(0, slash)), cpp_int(s.substr(slash + 1)));
bool neg = !s.empty() && s[0] == '-';
if (s[0] == '-' || s[0] == '+')
s.erase(s.begin());
auto p = s.find('.');
int k = p == string::npos ? 0 : s.size() - p - 1;
if (p != string::npos)
s.erase(p, 1);
size_t z = s.find_first_not_of('0');
cpp_int a = z == string::npos ? cpp_int(0) : cpp_int(s.substr(z));
return Q(neg ? -a : a, ten(k));
}
string fixedq(Q q, int digits) {
cpp_int a = q.numerator(), b = q.denominator(), scale = ten(digits);
bool neg = a < 0;
a = abig(a);
cpp_int k = (2 * a * scale + b) / (2 * b);
string s = k.convert_to<string>();
if (digits) {
if (s.size() <= digits)
s = string(digits + 1 - s.size(), '0') + s;
s.insert(s.size() - digits, ".");
}
return (neg && k != 0 ? "-" : "") + s;
}
string finiteq(Q q) {
cpp_int a = q.numerator(), b = q.denominator();
bool neg = a < 0;
a = abig(a);
cpp_int whole = a / b, r = a % b;
string s = whole.convert_to<string>();
if (r != 0) {
s += '.';
while (r != 0) {
r *= 10;
cpp_int z = r / b;
s += char('0' + z.convert_to<int>());
r %= b;
}
}
return (neg ? "-" : "") + s;
}
cpp_int isq(cpp_int n) {
if (n <= 0)
return 0;
cpp_int x = cpp_int(1) << ((boost::multiprecision::msb(n) + 2) / 2);
while (true) {
cpp_int y = (x + n / x) / 2;
if (y >= x)
return x;
x = y;
}
}
string scaled(cpp_int k, int d) {
bool neg = k < 0;
if (neg)
k = -k;
string s = k.convert_to<string>();
if (d) {
if (s.size() <= d)
s = string(d + 1 - s.size(), '0') + s;
s.insert(s.size() - d, ".");
}
return (neg && k != 0 ? "-" : "") + s;
}
int main() {
vector<cpp_int> a;
cpp_int x, S = 0, T = 0;
while (cin >> x) {
a.push_back(x);
S += x;
T += x * x;
}
sort(a.begin(), a.end());
cpp_int n = a.size();
for (int i = 0; i < (int)a.size(); i++)
cout << (i ? ", " : "") << a[i];
cout << '\n';
cpp_int v = (n * T - S * S) * 10000, k = isq(v / (n * n));
if (4 * v >= n * n * (2 * k + 1) * (2 * k + 1))
k++;
cout << fixedq(Q(S, n), 2) << ", " << scaled(k, 2) << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。