题面
https://www.luogu.org/problem/P5017
题解
#include<cstdio> #include<algorithm> #include<cstring> #include<iostream> using namespace std; long long n,m,f[155000],truetime[155000],t[550],nowt[550]; long long sum[155000],cnt[155000]; long long dp(int x){ if (x<=nowt[1]) return 0; else return f[x]; } long long count(int l,int r) { if (l<nowt[1]) l=0; long long s=sum[r]-sum[l],p=cnt[r]-cnt[l]; s-=p*truetime[l]; s=p*(truetime[r]-truetime[l])-s; return s; } int main(){ int i,j; scanf("%lld %lld",&n,&m); for (i=1;i<=n;i++) { scanf("%lld",&t[i]); t[i]+=500; } sort(t+1,t+n+1); t[0]=0; for (i=1;i<=n;i++) if (t[i]-t[i-1]>2*m) { nowt[i]=nowt[i-1]+2*m; truetime[nowt[i]]=t[i]; } else nowt[i]=nowt[i-1]+(t[i]-t[i-1]); for (i=1;i<=nowt[n]+500;i++) if (truetime[i]==0) truetime[i]=truetime[i-1]+1; for (i=1;i<=n;i++) { sum[nowt[i]]+=truetime[nowt[i]]; cnt[nowt[i]]++; } for (i=1;i<=nowt[n]+500;i++) sum[i]+=sum[i-1],cnt[i]+=cnt[i-1]; memset(f,0x3f,sizeof(f)); f[nowt[1]]=0; for (i=1;i<=nowt[n]+500;i++) for (j=i-m;j>=i-20*m;j--) if (dp(j)+count(j,i)<f[i]) f[i]=dp(j)+count(j,i); long long ans=987654321*987654321LL; for (i=nowt[n];i<=nowt[n]+500;i++) if (f[i]<ans) ans=f[i]; printf("%lld ",ans); }