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
 
题意:求n个数分成m个集合 要求花费的最小值
思路:我们首先要求出状态转移方程dp[i][j]=min(dp[i][j],dp[k][j-1]+(a[i]-a[k+1])^2) 这里我们可以用四边形不等式优化(打表可知)
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define ll long long int
using namespace std;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1};
int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1};
const int inf=0x3f3f3f3f;
const ll mod=1e9+7;
int dp[10007][5007]; //dp[i][j] 表示前i个人 分组成j组 
int s[10007][5007]; //决策数组 
int a[10007];
int main(){
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    int w=0;
    while(t--){
        int n,m;
        cin>>n>>m;
        for(int i=1;i<=n;i++){
            cin>>a[i];
        }
        sort(a+1,a+1+n); //排序后满足一个区间内的值是首尾的差平方 
        for(int i=1;i<=n;i++){ //初始化边界 
            dp[i][1]=(a[i]-a[1])*(a[i]-a[1]); //前i个人分成1组 
            s[i][1]=1; //初始化决策数组的左边界 
        }
        for(int j=2;j<=m;j++){
            s[n+1][j]=n-1; //初始化决策数组的右边界 
            for(int i=n;i>=j;i--){
                dp[i][j]=inf;
                for(int k=s[i][j-1];k<=s[i+1][j];k++){ //四边形不等式优化 
                    if(dp[i][j]>dp[k][j-1]+(a[i]-a[k+1])*(a[i]-a[k+1])){
                        dp[i][j]=dp[k][j-1]+(a[i]-a[k+1])*(a[i]-a[k+1]);
                        s[i][j]=k;
                    }
                }
            }
        }    
        cout<<"Case "<<++w<<": ";
        cout<<dp[n][m]<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wmj6/p/10714337.html