HDU 3480 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


Hint

The answer will fit into a 32-bit signed integer.

题解

二维的斜率优化,第一次写,原理还是差不多的,就是每次队列要从头开始。然后尽量用整数进行运算,常数会小。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<cmath>
#include<algorithm>
#define MAXN 10005
#define MAXM 5005
using namespace std;
int T,n,m,a[MAXN],f[MAXN][MAXM];
int q[MAXN],t,w;
void init()
{
	scanf("%d%d",&n,&m);
	int i;
	for(i=1;i<=n;i++) scanf("%d",&a[i]);
	sort(a+1,a+n+1);
}
int sqr(int x) {return x*x;}
int up(int k1,int k2,int j)
{
	return f[k2][j-1]+sqr(a[k2+1])-f[k1][j-1]-sqr(a[k1+1]);
}
int down(int k1,int k2)
{
	return 2*a[k2+1]-2*a[k1+1];
}
void dp()
{
	int i,j;
	for(i=1;i<=n;i++) f[i][1]=sqr(a[i]-a[1]);
	q[1]=1;
	for(j=2;j<=m;j++)
	   {t=1,w=1;
		for(i=j;i<=n;i++)
	       {while(t<w&&up(q[t],q[t+1],j)<=a[i]*down(q[t],q[t+1])) t++;
	        f[i][j]=f[q[t]][j-1]+sqr(a[i]-a[q[t]+1]);
	        while(t<w&&up(q[w],i,j)*down(q[w-1],q[w])<=up(q[w-1],q[w],j)*down(q[w],i)) w--;
		    q[++w]=i;
		   }
	   }
	printf("%d\n",f[n][m]);
}
int main()
{
	scanf("%d",&T);
	for(int c=1;c<=T;c++)
	   {init();
	    printf("Case %d: ",c);
	    dp();
	   }
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值