思路:动态规划。设dp[i][j][k]表示用第一个串的前i隔字符和第二个串的前k隔字符组成长度为i的串的个数,那么:若s1[j+1] == s2[k+1] dp[i+1][j+1][k+1] += dp[i][j][k],否则:dp[i+1][j+1][k] += dp[i][j][k]; dp[i+1][j][k+1] += dp[i][j][k]
#include<cstdio> #include<string> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int MAXN = 31; long long int dp[MAXN<<1][MAXN][MAXN]; char s1[MAXN], s2[MAXN]; int main(){ int t, CASE(0); scanf("%d", &t); while(t--){ scanf("%s%s", s1, s2); int len1 = strlen(s1), len2 = strlen(s2); memset(dp, 0, sizeof dp); dp[0][0][0] = 1; for(int i = 1;i <= len1+len2;i ++){ for(int j = 1;j <= len1+1;j ++){ for(int k = 1;k <= len2+1;k ++){ if(s1[j-1] == s2[k-1]) dp[i][j][k] += dp[i-1][j-1][k-1]; else{ dp[i][j][k-1] += dp[i-1][j-1][k-1]; dp[i][j-1][k] += dp[i-1][j-1][k-1]; } } } } int ans; for(int i = 1;i <= len1+len2;i ++){ if(dp[i][len1][len2]){ ans = i; break; } } printf("Case %d: %d %lld ", ++CASE, ans, dp[ans][len1][len2]); } return 0; }