hdu 3480 Division

http://acm.hdu.edu.cn/showproblem.php?pid=3480


这个题目的数据范围确实有点大,1000*5000,即使n*m的时间复查度也让人有点不敢做

思路: 排序,斜率优化即可

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
const int maxn=10010;
const int maxm=5010;
int dp[maxm][maxn],a[maxn],q[maxn];

int dy(int k,int j1,int j2)
{
    return dp[k][j2]+a[j2+1]*a[j2+1]-(dp[k][j1]+a[j1+1]*a[j1+1]);
}
int dx(int j1,int j2)
{
    return a[j2+1]-a[j1+1];
}
int main()
{
    int n,m,T,ca=1;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++) scanf("%d",&a[i]);
        if(m>=n){
           printf("Case %d: 0\n",ca++);
           continue;
        }
        sort(a+1,a+1+n);
        for(int i=1;i<=n;i++) dp[1][i]=(a[i]-a[1])*(a[i]-a[1]);
        for(int k=2;k<=m;k++)
        {
            int l=0,r=0;
            for(int i=1;i<=n;i++)
            {
                while(l+1<r&&dy(k-1,q[r-2],q[r-1])*dx(q[r-1],i-1)>=dy(k-1,q[r-1],i-1)*dx(q[r-2],q[r-1])) r--;
                q[r++]=i-1;
                while(l+1<r&&dy(k-1,q[l],q[l+1])<=dx(q[l],q[l+1])*2*a[i]) l++;
                dp[k][i]=dp[k-1][q[l]]+(a[i]-a[q[l]+1])*(a[i]-a[q[l]+1]);
            }
        }
        printf("Case %d: %d\n",ca++,dp[m][n]);
    }
    return 0;
}



你可能感兴趣的:(hdu 3480 Division)