题意:给定两行字符串,让你找出一个最短的序列,使得这两个字符串是它的子串,并且求出有多少种。
析:这个题和LCS很像,我们就可以利用这个思想,首先是求最短的长度,不就是两个字符串长度之和再减去公共的么。那么有多少种呢?
同样也是分两种情况讨论,如果s1[i-1] == s2[j-1] 那么种类数肯定和 ans[i-1][j-1]一样了,没有变化,再就是如果不相等怎么算呢?
难道也是ans[i][j] = Max(ans[i-1][j], ans[i][j-1])吗,其实并不是,如果两种方法数相等呢?也就是说从ans[i-1][j]能得到答案,也能从ans[i][j-1]得到答案,
所以要加起来。再就是要注意的是,字符串可能为空串,用gets输入。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f; const LL LNF = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 30 + 5; const int mod = 1e9 + 7; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline int Min(int a, int b){ return a < b ? a : b; } inline int Max(int a, int b){ return a > b ? a : b; } inline LL Min(LL a, LL b){ return a < b ? a : b; } inline LL Max(LL a, LL b){ return a > b ? a : b; } inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } char s1[maxn], s2[maxn]; int dp[maxn][maxn]; LL ans[maxn][maxn]; int main(){ int T; cin >> T; getchar(); for(int kase = 1; kase <= T; ++kase){ gets(s1+1); gets(s2+1); int len1 = strlen(s1+1); int len2 = strlen(s2+1); for(int i = 0; i <= len1; ++i) ans[i][0] = 1; for(int i = 0; i <= len2; ++i) ans[0][i] = 1; for(int i = 1; i <= len1; ++i){ for(int j = 1; j <= len2; ++j){ if(s1[i] == s2[j]){ dp[i][j] = dp[i-1][j-1] + 1; ans[i][j] = ans[i-1][j-1]; } else if(dp[i-1][j] > dp[i][j-1]){ dp[i][j] = dp[i-1][j]; ans[i][j] = ans[i-1][j]; } else if(dp[i-1][j] < dp[i][j-1]){ dp[i][j] = dp[i][j-1]; ans[i][j] = ans[i][j-1]; } else{ dp[i][j] = dp[i-1][j]; ans[i][j] = ans[i][j-1] + ans[i-1][j]; } } } printf("Case #%d: %d %lld ", kase, len1+len2-dp[len1][len2], ans[len1][len2]); } return 0; }