E54 斜率优化DP [NOIP2018 普及组] 摆渡车
视频链接:464 斜率优化DP [NOIP2018 普及组] 摆渡车_哔哩哔哩_bilibili
Luogu P5017 [NOIP2018 普及组] 摆渡车
#include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N=4e6+10; int n,m,last,q[N]; int c[N],s[N],f[N]; double slope(int i,int j){ return 1.0*(f[i]+s[i]-f[j]-s[j]) /(c[i]==c[j]?1e-9:c[i]-c[j]); } int main(){ scanf("%d%d",&n,&m); for(int i=1; i<=n; i++){ int t; scanf("%d",&t); c[t]++; s[t]+=t; last=max(last,t); } for(int i=1; i<last+m; i++) c[i]+=c[i-1],s[i]+=s[i-1]; for(int i=0;i<m;i++) f[i]=i*c[i]-s[i]; int h=1,t=0; int ans=1e9; for(int i=m; i<last+m; i++){ while(h<t && slope(i-m,q[t])<=slope(q[t],q[t-1])) t--; q[++t]=i-m; while(h<t && slope(q[h+1],q[h])<=i) h++; int j=q[h]; f[i]=f[j]+i*(c[i]-c[j])-(s[i]-s[j]); if(i>=last) ans=min(ans,f[i]); } printf("%d\n",ans); }