送上AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 505
int n, m, ans = inf;
int t[N], s[N], f[N][N];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
scanf("%d", t + i);
sort(t + 1, t + n + 1);
for (int i = 1; i <= n; i++)
s[i] = s[i - 1] + t[i];
t[0] = -inf;
memset(f, 0x3f, sizeof f);
f[0][0] = 0;
for (int i = 0; i <= n; i++) {
int mj = min(m - 1, t[i + 1] - t[i]);
for (int j = 0; j <= mj; j++)
if (f[i][j] != inf)
for (int k = 1; i + k <= n; k++) {
int now = max(t[i] + j + m - t[i + k], 0);
f[i + k][now] = min(f[i + k][now],
f[i][j] + (t[i + k] + now) * k - (s[i + k] - s[i]));
}
}
for (int i = 0; i < m; i++)
ans = min(ans, f[n][i]);
printf("%d\n", ans);
return 0;
}