标签:
题意:给出一个字符串和一个k,将字符串分成k段,每段的求法是sigma【(i − P OS) ∗ P OS】,问如何分段使得总和最小
思路:
设dp[i][j] 为将前j个字符分成i段的最小值。a[i]为第i个字符在原始字符串的位置。
那么dp[i][j] = min(dp[i][j],dp[i-1][k]+0*a[k+1]+1*a[k+2] + ...... + (j-k+1)*a[j] - a[k+1]^2 - ...... - a[j]^2)
==》k*a[k+1]+(k+1)*a[k+2] + ...... + (j-1)*a[j] - k*(a[k+1] + ....... + a[j]) - a[k+1]^2 - ...... - a[j]^2
用s1[]记录a[i]的和,s2[]记录(i-1)*a[i]的和,s3[]记录a[i]^2的和
然后就可以用斜率优化了
代码:
#include<cstdio> #include<algorithm> #include<iostream> #include<cstring> using namespace std; const int maxm = 505; const int maxn = 20005; int dp[maxm][maxn]; int key[30],n,m,a[maxn],s1[maxn],s2[maxn],s3[maxn]; int q[maxn],hd,tl; char str[maxn]; int getDP(int j,int k,int i){ return dp[i-1][k] + s2[j] - s2[k] - k*(s1[j]-s1[k]) - (s3[j]-s3[k]); } int getY(int j,int k,int i){ return (dp[i-1][k]-s2[k]+k*s1[k]+s3[k]) - (dp[i-1][j]-s2[j]+j*s1[j]+s3[j]); } int getX(int j,int k){ return k - j; } int solve(){ for(int j=1;j<=n;j++) dp[1][j] = s2[j] - s3[j]; for(int i=2;i<=m;i++){ hd = tl = 0; q[tl++] = i-1; for(int j=i;j<=n;j++){ while(hd+1<tl && getY(q[hd],q[hd+1],i) <= s1[j]*getX(q[hd],q[hd+1])) hd++; dp[i][j] = getDP(j,q[hd],i); while(hd+1<tl && getY(q[tl-1],j,i)*getX(q[tl-2],q[tl-1]) <= getY(q[tl-2],q[tl-1],i)*getX(q[tl-1],j)) tl--; q[tl++] = j; } } return dp[m][n]; } int main(){ int cas; scanf("%d",&cas); for(int T = 1; T <= cas; T++){ scanf("%s%d",str,&m); for(int i=0;i<strlen(str);i++){ key[str[i]-‘a‘] = i; } scanf("%s",str);n = strlen(str); a[1] = key[str[0]-‘a‘]; s1[1] = a[1];s2[1] = 0;s3[1] = a[1]*a[1]; for(int i=1;i<n;i++){ a[i+1] = key[str[i]-‘a‘]; s1[i+1] = s1[i] + a[i+1]; s2[i+1] = s2[i] + i*a[i+1]; s3[i+1] = s3[i] + a[i+1]*a[i+1]; } printf("Case %d: %d\n",T,solve()); } return 0; }
标签:
原文地址:http://www.cnblogs.com/Rojo/p/4699059.html