[HNOI2008][玩具装箱toy][斜率优化]

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

int const N= 50010;
int n, L;
typedef long long LL;
LL dp[N], sum[N], A[N], B[N]; 
int que[N], data[N];

/*
dp[i]= min{ dp[j]+ ( s[i]- s[j]+ i- j- 1- L )^2 }
令 A[i]= s[i]- i; B[j]= s[j]+ j+ 1+ L
原方程化为
dp[i]= min{ dp[j]+ ( A[i]- B[j] )* ( A[i]- B[j] ) } 
*/

LL G( int j, int k ){
	return dp[j]- dp[k]+ B[j]* B[j]- B[k]* B[k];
}

LL S( int j, int k ){
	return 2* ( B[j]- B[k] );
}

int main(){
	scanf("%d%d",&n,&L);
	for( int i= 1; i<= n; ++i ){
		scanf("%d", data+ i );
		sum[i]= sum[i-1]+ data[i];
	}
	for( int i= 1; i<= n; ++i ){
		A[i]=  sum[i]+ i;
		B[i]=  sum[i]+ i+ 1+ L;
	}B[0]= 1+ L;
	
	int head= 0, tail= 0; que[0]= 0;
	for( int i= 1; i<= n; ++i ){
		while( head< tail && G( que[head+ 1], que[head] )<= A[i]* S( que[head+ 1], que[head] ) )
		head++;
		
		dp[i]= dp[ que[head] ]+ ( A[i]- B[ que[head] ] )* ( A[i]- B[ que[head] ] );

		while( head< tail && G( que[tail], que[tail- 1] )* S( i, que[tail] )>=
		                     S( que[tail], que[tail- 1] )* G( i, que[tail] ) ) tail--;
		                     
		que[++tail]= i;
	}
	
	cout << dp[n] << endl;
	
	return 0;
}
 

你可能感兴趣的:(J#)