学习dp时在紫书发现的一个奇妙的题...
dp(i,j)并不能表示任意的长为i, j的两个串的L(c), 只有dp(lena, lenb)有意义...
因为任意ij后面的字符会影响开始/结束位置的数组...
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define ms(a) memset(a, -1, sizeof a) const int maxn = 5005, maxc = 26; char a[maxn], b[maxn]; int sta[maxc], stb[maxc], eda[maxc], edb[maxc]; int lena, lenb; int dp[maxn][maxn]; void init(){ ms(sta), ms(stb), ms(eda), ms(edb); for(int i = 1; i <= lena; i++){ int col = a[i]-‘A‘; if(sta[col] == -1) sta[col] = eda[col] = i; else eda[col] = i; } for(int i = 1; i <= lenb; i++){ int col = b[i]-‘A‘; if(stb[col] == -1) stb[col] = edb[col] = i; else edb[col] = i; } } void test(){ for(int i = 0; i < maxc; i++) if(sta[i]!=-1) printf("col:%c st:%d ed:%d\n", i+‘A‘, sta[i], eda[i]); for(int i = 0; i < maxc; i++) if(stb[i]!=-1) printf("col:%c st:%d ed:%d\n", i+‘A‘, stb[i], edb[i]); } void print(){ for(int i = 0; i <= lena; i++) for(int j = 0; j <= lenb; j++) printf("%d%c", dp[i][j], j == lenb ? ‘\n‘ : ‘ ‘); } int st_but_not_ed(int x, int y){ int cnt = 0; for(int i = 0; i < maxc; i++){ if(((sta[i] != -1 && sta[i] <= x) || (stb[i] != -1 && stb[i] <= y)) &&((eda[i] != -1 &&eda[i] > x) || (edb[i] != -1 && edb[i] > y))) cnt++; } return cnt; } int main(){ int t; scanf("%d", &t); while(t--){ scanf("%s%s", a+1, b+1); lena = strlen(a+1), lenb = strlen(b+1); init(); //test(); /*int q, qq; while(scanf("%d%d", &q, &qq)){ printf("%d\n", st_but_not_ed(q, qq)); }*/ for(int i = 0; i <= lena; i++) for(int j = 0; j <= lenb; j++){ if(!i&&!j) dp[i][j] = 0; else if(!i&&j) dp[i][j] = dp[i][j-1]+st_but_not_ed(i, j-1); else if(i&&!j) dp[i][j] = dp[i-1][j]+st_but_not_ed(i-1, j); else dp[i][j] = min(dp[i-1][j]+st_but_not_ed(i-1, j), dp[i][j-1]+st_but_not_ed(i, j-1)); //printf("%d ", dp[i][j]); } print(); //printf("%d\n", dp[lena][lenb]); } return 0; } /* 2 AAABBCY ABBBCDEEY GBBY YRRGB */