Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 999999/400000 K (Java/Others)
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.
题意:
n个数分成m组,每组的花费是(max_min)^2,求最小花费;
分析:
将前i个数分成j组,由前k个数分成j-1组转移而来,得到朴素DP方程:
设 ,且
移项,合并同类项,令
代入上述不等式,得:
然后进行斜率优化dp,这里用到了滚动数组
【Tips】斜率dp一般应用于连续的一段或几段求最值,即1~k,k+1~j,j+1~...这样分段而不能跳开来求,仅仅有连续段才能用单调队列维护凸包优化,然后更新dp[i]=dp[j]+(j+1~i)的值。
#include<bits/stdc++.h>
#define INF 0x7f7f7f7f
using namespace std;
const int maxn=1e4+7;
int q[maxn],a[maxn],dp[2][maxn];
int tmp=0,head,tail;
//dp[i][j]=min{dp[k][j-1]+(a[i]-a[k+1])^2};
int getdp(int i,int k) {return dp[tmp^1][k]+(a[i]-a[k+1])*(a[i]-a[k+1]);}
int getup(int k1,int k2) {return (dp[tmp^1][k1]+a[k1+1]*a[k1+1])-(dp[tmp^1][k2]+a[k2+1]*a[k2+1]);}
int getdown(int k1,int k2) {return 2*(a[k1+1]-a[k2+1]);}
int main()
{
int t;scanf("%d",&t);
for (int id=1;id<=t;id++)
{
int n,m;scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
sort(a+1,a+1+n);
tmp=0;
for (int i=1;i<=n;i++) dp[tmp][i]=INF;
for (int j=1;j<=m;j++)
{
tmp^=1;
head=tail=0;
q[tail++]=0;
for (int i=1;i<=n;i++)
{
while (head+1<tail && getup(q[head+1],q[head])<=a[i]*getdown(q[head+1],q[head])) head++;
dp[tmp][i]=getdp(i,q[head]);
while (head+1<tail && getup(i,q[tail-1])*getdown(q[tail-1],q[tail-2])<=getdown(i,q[tail-1])*getup(q[tail-1],q[tail-2])) tail--;
q[tail++]=i;
}
}
printf("Case %d: %d\n",id,dp[tmp][n]);
}
return 0;
}





被折叠的 条评论
为什么被折叠?



