Division
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 999999/400000 K (Java/Others)
Total Submission(s): 2676 Accepted Submission(s): 1056
Problem Description
Little D is really interested in the theorem of sets recently. There’s a problem that confused him a long time.
Let T be a set of integers. Let the MIN be the minimum integer in T and MAX be the maximum, then the cost of set T if defined as (MAX – MIN)^2. Now given an integer set S, we want to find out M subsets S1, S2, …, SM of S, such that
and the total cost of each subset is minimal.
Input
The input contains multiple test cases.
In the first line of the input there’s an integer T which is the number of test cases. Then the description of T test cases will be given.
For any test case, the first line contains two integers N (≤ 10,000) and M (≤ 5,000). N is the number of elements in S (may be duplicated). M is the number of subsets that we want to get. In the next line, there will be N integers giving set S.
Output
For each test case, output one line containing exactly one integer, the minimal total cost. Take a look at the sample output for format.
Sample Input
Sample Output
Case 1: 1 Case 2: 18
Hint
The answer will fit into a 32-bit signed integer.
Source
2010 ACM-ICPC Multi-University Training Contest(5)——Host by BJTU
题意:
将含有N个元素的一个集合分成M个子集,使得每个子集的最大值与最小值平方差的和最小。
思路1:
(斜率优化)
可以想到贪心将元素从小到大排序,很快可以得出dp[i][j]-前i个子集分j个元素的最小花费,
dp方程 dp[i][j]=dp[i-1][k]+(a[j]-a[k+1]);
但是需要三重循环,时间复杂度接受不了,所以需要优化,这题斜率优化和四边形不等式都可以,先看斜率优化。
设k1
化简得 ( dp[i-1][k1]+a[k1+1]^2-(dp[i-1][k2]+a[k2+1]^2) )/(a[k1+1]-a[k2+1])<=2a[j];
类比斜率,可以得出
y:dp[i-1][k1]+a[k1+1]^2;
x: a[k1+1];
于是和之前见到的斜率优化有了一个相同的式子 (y1-y2)/(x1-x2)
斜率优化可以用滚动数组实现,节约内存一些。
代码:
#include
#include
#include
#include
#include
#include
#include
思路2:(四边形不等式)
思路来源于:Staginner
有关四边形不等式的证明见赵爽的论文。
dp[i][j]=dp[i-1][k-1]+w[k][j],由于w[i+1][j]-w[i][j]=(a[i]-a[i+1])*(2*a[j]-a[i+1]-a[i]),这个表达式是随着j的增加单调递减的,所以就有w[i+1][j+1]-w[i][j+1]<=w[i+1][j]-w[i][j],也就是w[i][j]+w[i+1][j+1]<=w[i][j+1]+w[i+1][j],满足四边形不等式优化的条件,我们就可以放心地使用四边形不等式优化dp了。
对于dp[i][j]的决策s[i][j],有s[i][j-1]<=s[i][j]<=s[i+1][j],在dp[i][j]求出来之前要先求出dp[i][j-1]、dp[i+1][j],可以按照长度递增来递推,具体见代码,还有注意初始化。
代码:
#include
#include
#include
#include
#include
#include
#include