dp使用的过程中要做到无后效性,每一个值包含它对后面的影响
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
const int MAXN=10010;
#define ll long long
ll st[MAXN];
ll sf[MAXN];
ll dp[MAXN];
int q[MAXN];
int head,tail,n,m;
ll getDP(int i,int k)
{
return dp[k]+(st[i]-st[k]+m)*(sf[n]-sf[k]);
}
ll getUP(int k1,int k2) //yj-yk部分
{
return (dp[k1]-st[k1]*sf[n]+st[k1]*sf[k1]-m*sf[k1])-(dp[k2]-st[k2]*sf[n]+st[k2]*sf[k2]-m*sf[k2]);
}
ll getDOWN(int k1,int k2)
{
return sf[k1]-sf[k2];
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
int i,j;
int ta,tb;
st[0]=sf[0]=0;
for(i=1;i<=n;i++)
{
scanf("%lld%lld",&ta,&tb);
st[i]=st[i-1]+ta;
sf[i]=sf[i-1]+tb;
}
head=tail=0;
dp[0]=0;
q[tail++]=0;
for(i=1;i<=n;i++)
{
//把斜率转成相乘,注意顺序,否则不等号方向会改变的
while(head+1<tail && getUP(q[head+1],q[head])<=st[i]*getDOWN(q[head+1],q[head]))
head++;
dp[i]=getDP(i,q[head]);
while(head+1<tail && getUP(i,q[tail-1])*getDOWN(q[tail-1],q[tail-2])<=getUP(q[tail-1],q[tail-2])*getDOWN(i,q[tail-1]))
tail--;
q[tail++]=i;
}
printf("%d\n",dp[n]);
}
return 0;
}