现在的位置: 首页 > 综合 > 正文

HDU 3480 Division

2018年01月13日 ⁄ 综合 ⁄ 共 1779字 ⁄ 字号 评论关闭

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;
}

抱歉!评论已关闭.