記錄dp的設計。一開始設計的是f[i][j]表示最後一個選i,匹配到j的最大值,然而這樣轉移是\(n^2\)的,題目要求\(n*m\). 設計成0,1揹包,考慮第i個選擇或者不選擇即可。
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3 + 11;
int f[N][6];
int lef[N][6], val[N][6], to[N][6];
int len;
bool mark[N];
char s[N][N];
char S[] = {'n', 'a', 'r', 'e', 'k'};
void work(){
int n, m;
cin>>n>>m;
for(int i = 1;i <= n; i++){
scanf("%s", s[i]);
}
len = strlen(s[1]);
for(int i = 0;i <= 4; i++){
for(int j = 1;j <= n; j++){
lef[j][i] = 0;
int cnt = 0;
int pos = i;
for(int k = 0;k < len; k++){
if(s[j][k] == S[pos]){
pos++;
if(pos == 5)cnt += 1, pos -= 5;
}
else {
bool flag = false;
for(int l = 0;l < 5; l++)if(s[j][k] == S[l])flag = true;
lef[j][i] += flag;
}
}
to[j][i] = pos;
val[j][i] = 5 * cnt;
}
}
for(int i = 0;i <= n; i++){
for(int j = 0;j < 5; j++)f[i][j] = (i == 0 && j == 0) ? 0 : -1e8;
}
for(int i = 0;i < n; i++){
for(int j = 0;j < 5; j++)f[i+1][j] = f[i][j];
for(int j = 0;j < 5; j++){
f[i+1][to[i+1][j]] = max(f[i+1][to[i+1][j]], f[i][j] + val[i+1][j] - lef[i+1][j]);
}
}
int res = 0;
for(int j = 0;j < 5; j++){
res = max(res, f[n][j] - j);
}
cout<<res<<endl;
}
int main(){
int T;
cin>>T;
while(T--)work();
return 0;
}