BZOJ 4518: [Sdoi2016]征途

斜率优化

#include<cstdio>
#include<algorithm>
using namespace std;
int a[1000005],Sum[1000005];
long long F[2][1000005],G[2][1000005];
struct node{
	long long b,k;
}stack[1000005];
double check(node a,node b){
	return ((double)a.b-b.b)/(b.k-a.k);
}
int main(){
	int n,m;
	scanf("%d%d",&n,&m);
	for (int i=1; i<=n; i++) scanf("%d",&a[i]),Sum[i]=Sum[i-1]+a[i];
	long long ans=1ll*Sum[n]*Sum[n];
	for (int i=1; i<=n; i++) F[0][i]=G[0][i]=1ll<<60;
	for (int K=1; K<=m; K++){
		int head=1,tail=0;
		for (int i=0; i<=n; i++){
			node line=(node){G[(K-1)%2][i],-Sum[i]*2};
			while (tail>1 && check(stack[tail],stack[tail-1])>check(stack[tail],line)) tail--;
			stack[++tail]=line;
			while (tail-head>0 && check(stack[head],stack[head+1])<Sum[i]) head++;
			F[K%2][i]=stack[head].k*Sum[i]+stack[head].b;
//			F[K%2][i]=1ll<<60;
//			for (int j=0; j<=i; j++) F[K%2][i]=min(F[K%2][i],G[(K-1)%2][j]-2ll*Sum[j]*Sum[i]);
			F[K%2][i]+=1ll*Sum[i]*Sum[i],G[K%2][i]=F[K%2][i]+1ll*Sum[i]*Sum[i];
		}
	}
	ans=F[m%2][n]*m-ans;
	printf("%lld\n",ans);
	return 0;
}

  

posted @ 2018-10-18 19:18  ~Silent  阅读(181)  评论(0编辑  收藏  举报
Live2D