题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1501
题目大意:有 n 组数据, 每组数据三个字符串, 前两个字符串合成第三个字符串,要求原顺序不变, 问第三个字符串是否合法?
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <cstdlib> 6 #include <cmath> 7 #include <set> 8 #include <map> 9 #include <vector> 10 using namespace std; 11 12 int n, l1, l2, l, dp[210][210]; 13 char s1[210], s2[210], s[410]; 14 15 int dfs(int x, int y, int z) 16 { 17 int max = 0; 18 if(dp[x][y] != 0) 19 return dp[x][y]; 20 if(x == l1 && y == l2 && z == l) 21 return z;//这里注意是l1, 不是l1 - 1, 因为最后一位匹配成功后加了 1 22 if(x <= l1 && y <= l2 && z <= l) 23 { 24 if(s1[x] == s[z]) 25 { 26 int temp = dfs(x + 1, y, z + 1); 27 if(temp > max) 28 max = temp; 29 } 30 if(s2[y] == s[z]) 31 { 32 int temp = dfs(x, y + 1, z + 1); 33 if(temp > max) 34 max = temp; 35 } 36 if(s1[x] != s[z] && s2[y] != s[z]) 37 { 38 return z;//没有匹配的字符,返回 39 } 40 } 41 dp[x][y] = max; 42 return dp[x][y]; 43 } 44 int main() 45 { 46 scanf("%d", &n); 47 int cnt = 0; 48 while(n--) 49 { 50 cnt++; 51 memset(dp, 0, sizeof(dp)); 52 scanf("%s %s %s", s1, s2, s); 53 l1 = strlen(s1), l2 = strlen(s2), l = strlen(s); 54 string res = "no"; 55 int temp = dfs(0, 0, 0); 56 if(temp == l) 57 res = "yes"; 58 printf("Data set %d: ", cnt); 59 cout << res << endl; 60 } 61 return 0; 62 }