题目传送:Zipper
思路:设状态dp[i][j]为字符串A前i个字符和B前j个字符能否组成C的前i+j个字符,边界为dp[0][0] = 1能则为true,否则false
AC代码:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <cmath> #include <queue> #include <stack> #include <vector> #include <map> #include <set> #include <deque> #include <cctype> #define LL long long #define INF 0x7fffffff using namespace std; char A[205]; char B[205]; char C[405]; int T; int dp[205][205]; int main() { scanf("%d", &T); int cas = 1; while(T --) { scanf("%s %s %s", A + 1, B + 1, C + 1); int lena = strlen(A + 1); int lenb = strlen(B + 1); int lenc = strlen(C + 1); memset(dp, 0, sizeof(dp)); dp[0][0] = 1; for(int i = 0; i <= lena; i ++) { for(int j = 0; j <= lenb; j ++) { if(i > 0 && A[i] == C[i+j] && dp[i-1][j] == 1) { dp[i][j] = 1; } if(j > 0 && B[j] == C[i+j] && dp[i][j-1] == 1) { dp[i][j] = 1; } } } if(dp[lena][lenb] == 1) { printf("Data set %d: yes\n", cas ++); } else { printf("Data set %d: no\n", cas ++); } } return 0; }
刚开始的思路是算出A与C的LCS和B与C的LCS,如果满足A和B都是C的子序列的话且所有字母都相同数目一样则输出yes,但是有漏洞,比如ab, ab, baba,对于A是B或B是A的子串的时候就不对了
用LCS做的代码(贴一下,谨记):
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <cmath> #include <queue> #include <stack> #include <vector> #include <map> #include <set> #include <deque> #include <cctype> #define LL long long #define INF 0x7fffffff using namespace std; int T; char s1[205], s2[205], s3[405]; int num1[26], num2[26]; int dp[205][405], dp2[205][405]; int main() { scanf("%d", &T); int cas = 1; while(T --) { memset(num1, 0, sizeof(num1)); memset(num2, 0, sizeof(num2)); scanf("%s %s %s", s1 + 1, s2 + 1, s3 + 1); int len1 = strlen(s1 + 1); int len2 = strlen(s2 + 1); int len3 = strlen(s3 + 1); for(int i = 1; i <= len1; i ++) { num1[s1[i] - 'a'] ++; } for(int i = 1; i <= len2; i ++) { num1[s2[i] - 'a'] ++; } for(int i = 1; i <= len3; i ++) { num2[s3[i] - 'a'] ++; } printf("Data set %d: ", cas ++); int flag = 1; for(int i = 0; i < 26; i ++) { if(num1[i] != num2[i]) { flag = 0; break; } } if(flag == 0) { printf("no\n"); continue; } memset(dp, 0, sizeof(dp)); memset(dp2, 0, sizeof(dp2)); for(int i = 1; i <= len1; i ++) { for(int j = 1; j <= len3; j ++) { if(s1[i] == s3[j]) { dp[i][j] = dp[i-1][j-1] + 1; } else { dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } } for(int i = 1; i <= len2; i ++) { for(int j = 1; j <= len3; j ++) { if(s2[i] == s3[j]) { dp2[i][j] = dp2[i-1][j-1] + 1; } else { dp2[i][j] = max(dp2[i-1][j], dp2[i][j-1]); } } } if(dp[len1][len3] != len1 || dp2[len2][len3] != len2) { flag = 0; } if(flag) { printf("yes\n"); } else printf("no\n"); } return 0; }