Zipper
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6906 Accepted Submission(s): 2496
For example, consider forming "tcraete" from "cat" and "tree":
String A: cat
String B: tree
String C: tcraete
As you can see, we can form the third string by alternating characters from the two strings. As a second example, consider forming "catrtee" from "cat" and "tree":
String A: cat
String B: tree
String C: catrtee
Finally, notice that it is impossible to form "cttaree" from "cat" and "tree".
set per line.
For each data set, the line of input consists of three strings, separated by a single space. All strings are composed of upper and lower case letters only. The length of the third string is always the sum of the lengths of the first two strings. The first two
strings will have lengths between 1 and 200 characters, inclusive.
Data set n: yes
if the third string can be formed from the first two, or
Data set n: no
if it cannot. Of course n should be replaced by the data set number. See the sample output below for an example.
3 cat tree tcraete cat tree catrtee cat tree cttaree
Data set 1: yes Data set 2: yes Data set 3: no
简单dp,设dp[i][j]表示用第一个串的前i个字符和第二个串的前j个字符去表示第三个串的前i+j个字符的可行性,状态方程可以根据第三个串里每个字符的来源只有2种来确定
if (str1[i] == str3[i+j]) then dp[i][j] |= dp[i - 1][j]
if (str2[j] == str3[i+j]) then dp[i][j] |= dp[i][j - 1]
#include <map> #include <set> #include <list> #include <queue> #include <stack> #include <vector> #include <cmath> #include <cstdlib> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N = 210; char str1[N], str2[N], str3[N << 1]; bool dp[N][N]; int main() { int t, icase = 1; scanf("%d", &t); while (t--) { memset (dp, 0, sizeof(dp)); scanf("%s%s%s", str1, str2, str3); int len1 = strlen(str1); int len2 = strlen(str2); int i = 0; while (i < len1) { if (str1[i] == str3[i]) { dp[i + 1][0] = 1; i++; } else { break; } } i = 0; while (i < len2) { if (str2[i] == str3[i]) { dp[0][i + 1] = 1; i++; } else { break; } } for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (str1[i - 1] == str3[i + j - 1]) { dp[i][j] |= dp[i - 1][j]; } if (str2[j - 1] == str3[i + j - 1]) { dp[i][j] |= dp[i][j - 1]; } } } if (dp[len1][len2]) { printf("Data set %d: yes\n", icase++); } else { printf("Data set %d: no\n", icase++); } } return 0; }