码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3709 K-Anonymous Sequence

时间:2017-02-01 21:48:35      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:ons   oid   git   typedef   iostream   ios   bool   comm   min   

$dp$,斜率优化。

设$dp[i]$表示前$i$个位置调整成$K-Anonymous$的最小花费。

那么,$dp[i]=min(dp[j]+sum[i]-sum[j]-x[j+1]*(i-j))$。

直接算是$O(n^2)$,进行斜率优化即可。

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<ctime>
#include<iostream>
using namespace std;
typedef long long LL;
const double pi=acos(-1.0),eps=1e-10;
void File()
{
    freopen("D:\\in.txt","r",stdin);
    freopen("D:\\out.txt","w",stdout);
}
template <class T>
inline void read(T &x)
{
    char c = getchar();
    x = 0;
    while(!isdigit(c)) c = getchar();
    while(isdigit(c))
    {
        x = x * 10 + c - 0;
        c = getchar();
    }
}

int n,k,T;
long long x[500010],sum[500010],dp[500010];
int f1,f2,q[500010];

bool delete1(int a,int b,int c)
{
    if(dp[b]-sum[b]+b*x[b+1]-c*x[b+1]<=
       dp[a]-sum[a]+a*x[a+1]-c*x[a+1]
       ) return 1;
    return 0;
}

bool delete2(int a,int b,int c)
{
    if(
       ((dp[c]-sum[c]+c*x[c+1])-(dp[b]-sum[b]+b*x[b+1]))*(x[b+1]-x[a+1])<=
       ((dp[b]-sum[b]+b*x[b+1])-(dp[a]-sum[a]+a*x[a+1]))*(x[c+1]-x[b+1])
       ) return 1;
    return 0;
}

int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&k);
        for(int i=1;i<=n;i++)
        {
            scanf("%lld",&x[i]);
            sum[i]=sum[i-1]+x[i];
        }

        for(int i=k;i<2*k;i++) dp[i]=sum[i]-i*x[1];

        f1=0; f2=1; q[0]=0; q[1]=k;

        for(int i=2*k;i<=n;i++)
        {
            while(1)
            {
                if(f2-f1+1<2) break;
                if(delete1(q[f1],q[f1+1],i)) f1++;
                else break;
            }

            dp[i]=dp[q[f1]]+sum[i]-sum[q[f1]]-(i-q[f1])*x[q[f1]+1];

            while(1)
            {
                if(f2-f1+1<2) break;
                if(delete2(q[f2-1],q[f2],i-k+1)) f2--;
                else break;
            }

            f2++;
            q[f2]=i-k+1;
        }

        printf("%lld\n",dp[n]);
    }
    return 0;
}

 

POJ 3709 K-Anonymous Sequence

标签:ons   oid   git   typedef   iostream   ios   bool   comm   min   

原文地址:http://www.cnblogs.com/zufezzt/p/6360358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!