杭电1501_dfs和记忆化搜索

题目链接: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 }

 

转载于:https://www.cnblogs.com/luomi/p/5512503.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值