「BZOJ2428」[HAOI2006]均分数据

Description

已知NN个正整数:A1A_1A2A_2\cdotsAnA_n 。今要将它们分成MM组,使得各组数据的数值和最平均,即各组的均方差最小。均方差公式如下:

σ=1m(xˉxi)m\sigma=\sqrt{\frac{\sum_1^m(\bar{x}-x_i)}{m}}

xˉ=1mxim\bar{x}=\frac{\sum_1^m x _i}{m}

Input

第一行是两个整数,表示N,MN,M的值(NN是整数个数,MM是要分成的组数)
第二行有NN个整数,表示A1A_1A2A_2\cdotsAnA_n。整数的范围是1501\sim50
(同一行的整数间用空格分开)

Output

这一行只包含一个数,表示最小均方差的值(保留小数点后两位数字)。

Sample Input

1
2
6  3
1 2 3 4 5 6

Sample Output

1
0.00

HINT

对于全部的数据,保证有KN20,2K6K\leq N \leq 20,2\leq K\leq 6.

Solution

模拟退火。随机选择位置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<map>
#include<cmath>
#include<queue>
#include<ctime>
#include<bitset>
#define mk make_pair
#define fi first
#define nd second
#define pii pair<int,int>
#define pb push_back
#define sqr(x) ((x)*(x))
using namespace std;
typedef long long ll;
inline ll read() {ll x = 0; char ch = getchar(), w = 1;while(ch < '0' || ch > '9') {if(ch == '-') w = -1;
ch = getchar();}while(ch >= '0' && ch <= '9') {x = x * 10 + ch - '0';ch = getchar();}return x * w;}
void write(ll x) {if(x < 0) putchar('-'), x = -x;if(x > 9) write(x / 10);putchar(x % 10 + '0');}
inline void writeln(ll x) {write(x);puts("");}
const int N = 25;
int a[N], n, m;
int sum, s[N];
int ans;
int f[N][8];
int cal() {
memset(f,0x3f,sizeof f);
for(int i = 1; i <= n; ++i) s[i] = s[i - 1] + a[i];
f[0][1] = 0;
for(int i = 1; i <= n; ++i) {
f[i][1] = sqr(s[i]);
for(int j = 2; j <= i && j <= m; ++j)
for(int k = 0; k < i; ++k) if(k >= j - 1)
f[i][j] = min(f[i][j], f[k][j - 1] + sqr(s[i] - s[k]));
}
return f[n][m];
}
double Rand() {
return (double)rand() / RAND_MAX;
}
void SA(double T) {
int now = ans;
while(T > 0.001) {
int x = rand() % n + 1, y = rand() % n + 1;
if(x == y) continue;
swap(a[x], a[y]);
int tmp = cal();
if(tmp < now || exp(now - tmp) / T > Rand()) now = tmp;
else swap(a[x], a[y]);
T = T * 0.99;
}
for(int i = 1; i <= 10000; ++i) {
int x = rand() % n + 1, y = rand() % n + 1;
if(x == y) continue;
swap(a[x], a[y]);
int tmp = cal();
now = min(now, tmp);
swap(a[x], a[y]);
}
ans = now;
}
static int START;
double Tim() {
return (double)(clock() - START) / CLOCKS_PER_SEC;
}
int main() {
srand(time(NULL));
START = clock();
double res = 0;
ans = 1e9;
n = read(), m = read();
for(int i = 1; i <= n; ++i) a[i] = read(), res += a[i];
res = m * sqr(res / m) - 2 * res/ m * res;
ans = cal();
while(Tim() < 0.75)
SA(10000);
while(Tim() < 0.9) {
random_shuffle(a + 1, a + 1 + n);
ans = min(ans, cal());
}
res += ans;
res /= m;
printf("%.2lf\n", sqrt(res));
return 0;
}