https://blog.sengxian.com/solutions/noip-2015-day2
三维DP,空间会爆,缩范围可拿70巨分。
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn = 550;
const int maxm = 55;
const int mod = 1000000007;
int n, m, K;
char a[maxn], b[maxm];
int f[maxn][maxm][maxm], s[maxn][maxm][maxm];
int main(){
cin >> n >> m >> K;
scanf("%s", a+1);
scanf("%s", b+1);
s[0][0][0] = 1;
for(int i = 1; i <= n; i++){
s[i][0][0] = 1;
for(int j = 1; j <= m; j++){
if(a[i] == b[j])
for(int k = 1; k <= min(K, j); k++){
f[i][j][k] = (s[i-1][j-1][k-1] + f[i-1][j-1][k]) % mod;
s[i][j][k] = (s[i-1][j][k] + f[i][j][k]) % mod;
}
else
for(int k = 1; k <= min(K, j); k++)
s[i][j][k] = s[i-1][j][k];
}
}
cout << s[n][m][K] << endl;
return 0;
}
三维可像01背包一样压缩为二维,方法是倒序枚举j,k,这样可以调用i-1时的j,k,如此可拿100巨分。
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn = 1050;
const int maxm = 220;
const int mod = 1000000007;
int n, m, K;
char a[maxn], b[maxm];
int f[maxm][maxm], s[maxm][maxm];
int main(){
cin >> n >> m >> K;
scanf("%s", a+1);
scanf("%s", b+1);
s[0][0] = 1;
for(int i = 1; i <= n; i++){
//s[i][0][0] = 1;
for(int j = m; j >= 1; j--){
if(a[i] == b[j])
for(int k = min(K, j); k >= 1; k--){
f[j][k] = (s[j-1][k-1] + f[j-1][k]) % mod;
s[j][k] = (s[j][k] + f[j][k]) % mod;
}
else
fill(f[j], f[j] + min(K, j) + 1, 0);
}
}
cout << s[m][K] << endl;
return 0;
}