Poj 3709 K-Anonymous Sequence slope optimization dp

Source: Internet
Author: User

#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn=5e5+9;long long a[maxn];long long dp[maxn],sum[maxn];int que[maxn];bool chk1(int k,int j,int i){    long long s1=(dp[j]-sum[j]+a[j+1]*j)-(dp[k]-sum[k]+a[k+1]*k);    s1*=(a[i+1]-a[j+1]);    long long s2=(dp[i]-sum[i]+a[i+1]*i)-(dp[j]-sum[j]+a[j+1]*j);    s2*=(a[j+1]-a[k+1]);    return s1>s2;}bool chk2(int k,int j,int i){    long long s=(dp[j]-sum[j]+a[j+1]*j)-(dp[k]-sum[k]+a[k+1]*k);    return s<=(a[j+1]-a[k+1])*i;}int main(){//    freopen("in.txt","r",stdin);    int T;    scanf("%d",&T);    while(T--)    {        int n,m;        scanf("%d %d",&n,&m);        sum[0]=0;        for(int i=1;i<=n;i++)        {            scanf("%lld",&a[i]);            a[i]++;            sum[i]=sum[i-1]+a[i];        }        int front=1,end=0;        dp[m]=sum[m]-a[1]*m;        que[++end]=0;        dp[0]=0;        for(int i=1;i+m<=n;i++)        {            if(i>=m)            {                if(a[i+1]==a[que[end]+1])                {                    if(dp[i]<dp[que[end]])                    {                        end--;                        while(front<end&&chk1(que[end-1],que[end],i))                        end--;                        que[++end]=i;                    }                }                else                {                    while(front<end&&chk1(que[end-1],que[end],i))                    end--;                    que[++end]=i;                }            }            while(front<end&&chk2(que[front],que[front+1],i+m))            front++;            int u=que[front];            dp[i+m]=dp[u]+sum[i+m]-sum[u]-a[u+1]*(i+m-u);        }        printf("%lld\n",dp[n]);    }    return 0;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.