HDU 3480 Division

Division


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
 
   
2 3 2 1 2 4 4 2 4 7 10 1
 

Sample Output
 
   
Case 1: 1 Case 2: 18


题意就是给出一个n个元素的集合  分成m个子集使得所有子集的cost之和最小,每个子集的cost为子集中最大元素减去最小元素的平方。

先排序,再dp,dp[i][j]表示前j个元素分成i个子集的最小cost,dp[i][j] = min(dp[i][k]+(a[j]-a[k+1])*(a[j]-a[k+1])) ,效率为n^3,显然超时,注意到w[i][j]    是关于区间包含关系单调,采用四边形不等式优化,k的范围取在s[i-1][j] , s[i][j+1] 之间,优化后效率为n^2。再就是关于数组大小问题,dp与s开10010*5010也可以过,但作为练习,滚动数组还是要学会的。


#include 
#include 
#include 
#include 
using namespace std;

#define maxn 10010
int n,m,a[maxn];
int dp[2][maxn];
int s[2][maxn];

void solve(){
	int t = 0;
	for(int i=1;i<=n;i++){
		dp[t][i] = (a[i]-a[1])*(a[i]-a[1]);
		s[t][i] = 0;
	}
	t ^=1;
	for(int i=2;i<=m;i++){
		s[t][n+1]=n;
		for(int j=n;j>=i;j--){
			int x = s[t^1][j] , y = s[t][j+1];
			for(int k=x;k<=y;k++){
				int tmp = (a[j]-a[k+1])*(a[j]-a[k+1]);
				if(dp[t][j]>dp[t^1][k]+tmp){
					dp[t][j] = dp[t^1][k] + tmp;
					s[t][j] = k;
				}
			}
		}
		t^=1;
	}
	cout << dp[t^1][n] <> T;
	while(T--){
		cin >> n >> m;
		memset(dp,0x3f3f,sizeof(dp));
		for(int i=1;i<=n;i++) scanf("%d",&a[i]);
		sort(a+1,a+n+1);
		printf("Case %d: ",cas++);
		solve();
	}
	return 0;
}





你可能感兴趣的:(ACM刷题记录)