B. Minimization
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n.
You need to permute the array elements so that value
Input
The first line contains two integers n, k (2 ≤ n ≤ 3·105, 1 ≤ k ≤ min(5000, n - 1)).
The second line contains n integers A[1], A[2], ..., A[n] ( - 109 ≤ A[i] ≤ 109), separate by spaces — elements of the array A.
Output
Print the minimum possible value of the sum described in the statement.
Sample test(s)
input
3 2 1 2 4
output
1
input
5 2 3 -5 3 -5 3
output
0
input
6 3 4 3 4 3 2 5
output
3
Note
In the first test one of the optimal permutations is 1 4 2.
In the second test the initial order is optimal.
In the third test one of the optimal permutations is 2 3 4 4 3 5.
思路:
令sz = n/k
可以发现:
有n % k个长度为sz + 1的,有k - n % k 个长度为sz的
dp[i][j]表示取i个长度为sz + 1的和j个长度为sz的最小代价
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
#define LL __int64
const LL INF = 10000000000000000LL;
const int N = 3 * 1e5 + 5;
const int M = 5005;
LL a[N], pre[N];
LL dp[M][M];
void init(int n) {
pre[0] = pre[1] = 0;
for(int i = 2; i <= n; ++i) {
pre[i] = pre[i - 1] + a[i] - a[i - 1];
}
for(int i = 0; i < M; ++i) {
for(int j = 0; j < M; ++j) {
dp[i][j] = INF;
}
}
}
int main() {
int n, k;
cin>>n>>k;
for(int i = 1; i <= n; ++i)
cin>>a[i];
sort(a + 1, a + 1 + n);
int sz = n / k;
int u = n % k;
int v = k - u;
init(n);
dp[0][0] = 0;
for(int i = 0; i <= u; ++i) {
for(int j = 0; j <= v; ++j) {
int x = i * (sz + 1) + j * sz + 1;
dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + pre[x + sz] - pre[x]);
dp[i][j + 1] = min(dp[i][j + 1], dp[i][j] + pre[x + sz - 1] - pre[x]);
}
}
cout<<dp[u][v]<<endl;
return 0;
}