$dp$,斜率优化。
设$dp[i]$表示前$i$个位置调整成$K-Anonymous$的最小花费。
那么,$dp[i]=min(dp[j]+sum[i]-sum[j]-x[j+1]*(i-j))$。
直接算是$O(n^2)$,进行斜率优化即可。
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<map> #include<set> #include<queue> #include<stack> #include<ctime> #include<iostream> using namespace std; typedef long long LL; const double pi=acos(-1.0),eps=1e-10; void File() { freopen("D:\\in.txt","r",stdin); freopen("D:\\out.txt","w",stdout); } template <class T> inline void read(T &x) { char c = getchar(); x = 0; while(!isdigit(c)) c = getchar(); while(isdigit(c)) { x = x * 10 + c - ‘0‘; c = getchar(); } } int n,k,T; long long x[500010],sum[500010],dp[500010]; int f1,f2,q[500010]; bool delete1(int a,int b,int c) { if(dp[b]-sum[b]+b*x[b+1]-c*x[b+1]<= dp[a]-sum[a]+a*x[a+1]-c*x[a+1] ) return 1; return 0; } bool delete2(int a,int b,int c) { if( ((dp[c]-sum[c]+c*x[c+1])-(dp[b]-sum[b]+b*x[b+1]))*(x[b+1]-x[a+1])<= ((dp[b]-sum[b]+b*x[b+1])-(dp[a]-sum[a]+a*x[a+1]))*(x[c+1]-x[b+1]) ) return 1; return 0; } int main() { scanf("%d",&T); while(T--) { scanf("%d%d",&n,&k); for(int i=1;i<=n;i++) { scanf("%lld",&x[i]); sum[i]=sum[i-1]+x[i]; } for(int i=k;i<2*k;i++) dp[i]=sum[i]-i*x[1]; f1=0; f2=1; q[0]=0; q[1]=k; for(int i=2*k;i<=n;i++) { while(1) { if(f2-f1+1<2) break; if(delete1(q[f1],q[f1+1],i)) f1++; else break; } dp[i]=dp[q[f1]]+sum[i]-sum[q[f1]]-(i-q[f1])*x[q[f1]+1]; while(1) { if(f2-f1+1<2) break; if(delete2(q[f2-1],q[f2],i-k+1)) f2--; else break; } f2++; q[f2]=i-k+1; } printf("%lld\n",dp[n]); } return 0; }
时间: 2024-10-13 03:27:09