Division HDU - 3480 区间dp 与 四边形不等式优化 或者 斜率优化

 

博客目录

原题

题目传送门

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.

解析

占坑待补

区间dp 与 四边形不等式优化 学习笔记

AC代码(斜率优化)

#include
#include
using namespace std;
/*

dp[i][j]


*/
#define cost(a,b) (co[b]-co[a])*(co[b]-co[a])
int const maxn=1e4+10;
int co[maxn];
int dp[maxn];
int cnt[maxn];
int s[maxn][5000+10];
int main()
{
    int n,m;
    int T,i,j;
    cin>>T;
    int cas=1;
    while(T--)
    {
        cin>>n>>m;
        for(i=1;i<=n;i++)
        {
            scanf("%d",co+i);
        }
        sort(co+1,co+n+1);
        memset(dp,0x7f,sizeof(dp));
        memset(s,0,sizeof(s));
        int k;
        dp[0]=0;
        for(i=1;i<=n;i++)
        	dp[i]=cost(1,i);
        for(i=0;i<=n;i++)
			s[i][1]=1; 
        for(j=2;j<=m;j++)
        {
        	s[n+1][j]=n;
        	for(i=n;i>=1;i--)
            {
                for(k=s[i][j-1];k<=s[i+1][j];k++)//dp[i]=min(dp[k]+cost[k+1][i],dp[i]),0<=kdp[k]+cost(k+1,i))
                    {
                        dp[i]=dp[k]+cost(k+1,i);
                        s[i][j]=k;
                    }
                }
            }
		}
            
        printf("Case %d: " ,cas++);
        cout<

 

你可能感兴趣的:(区间dp)