HDU 3480 DP斜率优化 解题报告

来源:互联网 发布:js修改style属性值 编辑:程序博客网 时间:2024/05/16 17:08

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

【解题报告】
题目要求m个子数组的最值,而子数组中的元素不一定是原数组连续的
所以肯定不能直接用斜率优化,经过分析可以发现先进行从小到大排序
然后连续的m段最值就是可以求最值了。

所以:先对原数组进行从小到大排序
dp[i][j]表示以i结尾的j段的最值
从k+1~i作为一段
则:dp[i][j]=dp[k][j-1]+(s[i]-s[k+1])^2
现在就是如何求到这个k使得dp[i][j]最小
假设k2<=k1 < i
若:dp[k1][j-1]+(s[i]-s[k1+1])^2 <= dp[k2][j-1]+(s[i]-s[k2+1])^2
=>dp[k1][j-1]+s[k1+1]^2 - (dp[k2][j-1]+s[k2+1]^2) / (2s[k1+1]-2s[k2+1]) <= s[i]
所以:
y1 = dp[k1][j-1]+s[k1+1]^2
x1 = 2s[k1+1]
y2 = dp[k2][j-1]+s[k2+1]^2
x2 = 2s[k2+1]

=>(y1 - y2)/(x1 - x2) <= i
单调队列维护下凸折线

代码如下:

#include<cstdio>  #include<cstring>  #include<algorithm>  #include<cmath>  #define INF 99999999 #define MAX 10010using namespace std;  int n,m,index;  int q[MAX];  int s[MAX],dp[2][MAX];//采用滚动数组  int GetY(int k1,int k2){      return dp[index^1][k1]+s[k1+1]*s[k1+1] - (dp[index^1][k2]+s[k2+1]*s[k2+1]);  }  int GetX(int k1,int k2){      return 2*(s[k1+1]-s[k2+1]);  }  int DP(){      int head=0,tail=1;      index=0;      for(int i=1;i<=n;++i) dp[index][i]=INF;//初始化        for(int i=1;i<=m;++i)    {          index=index^1;          head=tail=0;          q[tail++]=0;          for(int j=1;j<=n;++j)        {              while(head+1<tail&&GetY(q[head+1],q[head])<=GetX(q[head+1],q[head])*s[j]) ++head;              while(head+1<tail&&GetY(j,q[tail-1])*GetX(q[tail-1],q[tail-2])<=GetY(q[tail-1],q[tail-2])*GetX(j,q[tail-1])) --tail;              q[tail++]=j;              int k=q[head];              dp[index][j]=dp[index^1][k]+(s[j]-s[k+1])*(s[j]-s[k+1]);          }      }      return dp[index][n];  }  int main(){      int t,num=0;      for(scanf("%d",&t);t;t--)    {          scanf("%d%d",&n,&m);          for(int i=1;i<=n;++i) scanf("%d",s+i);          sort(s+1,s+1+n);          printf("Case %d: %d\n",++num,DP());      }      return 0;  }   

让我看到你们的双手

0 0
原创粉丝点击