标签:tps http namespace net include max ++ code 等价
参考博客https://blog.csdn.net/qq_26572969/article/details/47155559
//设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],l,r;
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++) {
l = r = 0;
q[0] = i-1;
for(int j=i; j<=n; j++) {
while(l<r && getY(q[l],q[l+1],i) <= s1[j]*getX(q[l],q[l+1]))
l++;
dp[i][j] = getDP(j,q[l],i);
while(l<r && getY(q[r],j,i)*getX(q[r-1],q[r]) <= getY(q[r-1],q[r],i)*getX(q[r],j))
r--;
q[++r] = 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;
}
Naming Babies UVA - 12594 斜率dp
标签:tps http namespace net include max ++ code 等价
原文地址:https://www.cnblogs.com/QingyuYYYYY/p/12519017.html