Print Article

HDU

题意:长度为\(N(N<=500000)\)的序列,序列中每个元素为\(c_i\),将序列分成若干批,每一批的代价为\((\sum c_i)^2+M\),M是一个已知常数.

分析:设\(f[i]\)表示将前i个元素分成若干批的最小代价,\(f[i]=f[j]+(sum[i]-sum[j])^2+M\)

\(k<j\)且j比k更优,则有,

\(f[j]+(sum[i]-sum[j])^2+M<f[k]+(sum[i]-sum[k])^2+M\)

整理一下上式得到,

\(\frac{f[j]+sum[j]^2-f[k]-sum[k]^2}{sum[j]-sum[k]}<2sum[i]\)

//#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
#include<cstdio>
#define LL long long
using namespace std;
inline int read(){
    int s=0,w=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){s=s*10+ch-'0';ch=getchar();}
    return s*w;
}
const int N=500005;
int n,m,l,r,c[N],q[N];
LL sum[N],f[N];
inline LL count(int x,int y){return f[x]+sum[x]*sum[x]-f[y]-sum[y]*sum[y];}
int main(){
    while((scanf("%d %d",&n,&m))!=EOF){
		for(int i=1;i<=n;i++){
	    	f[i]=0;q[i]=0;
	    	c[i]=read();
	    	sum[i]=sum[i-1]+c[i];
		}
		l=1,r=1;
		for(int i=1;i<=n;i++){
	    	while(l<r&&count(q[l+1],q[l])<=2*sum[i]*(sum[q[l+1]]-sum[q[l]]))l++;	   
	    	f[i]=f[q[l]]+(sum[i]-sum[q[l]])*(sum[i]-sum[q[l]])+m;
	    	while(l<r&&count(q[r],q[r-1])*(sum[i]-sum[q[r]])>=count(i,q[r])*(sum[q[r]]-sum[q[r-1]]))r--;
	    	q[++r]=i;
		}
		printf("%lld\n",f[n]);
    }
    return 0;
}

posted on 2019-06-12 08:25  PPXppx  阅读(139)  评论(0编辑  收藏  举报