居然搞错斜率优化的概念。。(打脸3次啪啪啪)
先出方程,a[i]为p[i]的前缀和,b[i]为p[i]*x[i]的前缀和
f[i]=f[j]+(a[i]-a[j])x[i]+b[j]-b[i]+c[i]
=f[j]+b[j]-a[j]x[i]+a[i]-b[i]+c[i]
当J比k优,得f[j]-f[k]-a[j]x[i]+a[k]x[i]+b[j]-b[k]<0
(f[j]+b[j]-f[k]-b[k])/(a[j]-a[k])<x[i]
这样就维护一个上凸函数(是上凸还是下凸有点乱,有错请纠正一下thx)
好像还有一种做法把f[i]表示成了截距,不过还是要用斜率,这样就变成维护下凸函数(有点线性规划的味道)
= =要注意slope(x,y)看似x,y是能互换其实是不能的(当a[j]==a[k]的话)
1 #include<bits/stdc++.h> 2 #define inc(i,l,r) for(int i=l;i<=r;i++) 3 #define dec(i,l,r) for(int i=l;i>=r;i--) 4 #define link(x) for(edge *j=h[x];j;j=j->next) 5 #define mem(a) memset(a,0,sizeof(a)) 6 #define inf 1e9 7 #define ll long long 8 #define succ(x) (1<<x) 9 #define NM 1000000+5 10 using namespace std; 11 int read(){ 12 int x=0,f=1;char ch=getchar(); 13 while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} 14 while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); 15 return x*f; 16 } 17 int n,x[NM],c[NM],q[NM],qh,qt,t; 18 ll f[NM],a[NM],b[NM]; 19 double slope(int l,int r){ 20 return (double)(f[l]+b[l]-f[r]-b[r])/(a[l]-a[r]); 21 } 22 int main(){ 23 freopen("data.in","r",stdin); 24 n=read(); 25 inc(i,1,n){ 26 x[i]=read();t=read();c[i]=read(); 27 a[i]=a[i-1]+t;b[i]=b[i-1]+(ll)x[i]*t; 28 } 29 qh=qt=1;q[qh]=0; 30 inc(i,1,n){ 31 while(qh+1<=qt&&slope(q[qh+1],q[qh])<x[i])qh++; 32 t=q[qh]; 33 f[i]=f[t]+(a[i]-a[t])*x[i]+b[t]-b[i]+c[i]; 34 while(qh+1<=qt&&slope(q[qt],q[qt-1])>=slope(i,q[qt]))qt--; 35 q[++qt]=i; 36 } 37 // inc(i,1,n)printf("%d ",f[i]);printf("\n"); 38 printf("%lld\n",f[n]); 39 return 0; 40 }