HDU 6170 Two strings (二维DP)

来源:互联网 发布:南京大学网络教育2017 编辑:程序博客网 时间:2024/05/17 04:22

Two strings

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 626    Accepted Submission(s): 245


Problem Description
Giving two strings and you should judge if they are matched.
The first string contains lowercase letters and uppercase letters.
The second string contains lowercase letters, uppercase letters, and special symbols: “.” and “*”.
. can match any letter, and * means the front character can appear any times. For example, “a.b” can match “acb” or “abb”, “a*” can match “a”, “aa” and even empty string. ( “*” will not appear in the front of the string, and there will not be two consecutive “*”.
 

Input
The first line contains an integer T implying the number of test cases. (T≤15)
For each test case, there are two lines implying the two strings (The length of the two strings is less than 2500).
 

Output
For each test case, print “yes” if the two strings are matched, otherwise print “no”.
 

Sample Input
3aaa*abba.*abbaab
 

Sample Output
yesyesno
 

Source
2017 Multi-University Training Contest - Team 9
 

Recommend
liuyiding
 


题目大意:


给出两个字符串,第一个字符串只包含小写或者大写字母,第二个字符串包含小写或者大写字母或者特殊字符“.”和“*”,这里“.”可以替换为任意字符,但是不能变成空。

这里“a*”可以变成空串,可以变成a,也可以是aa,也可以是aaa,还可以是aaaa.以此类推,不限长度。

问第二个串和第一个串是否能够完全相等。


思路:

就是一个常规的二位DP啊啊啊啊啊。。。。

DP[i][j] 表示串1前i个与串2前j个是否匹配成功...这个转移自己想的话也很简单想,类似于公共子序列, 如果s1[i] == s2[j] 或者 s2[j] == '.'就只与dp[i-1[j-1]有关, 唯一稍微麻烦点的地方在*上, 如果s2[j] = '*',那么如果一个也不匹配 就是 dp[i][j-2],等于把这两个跳过去了,如果匹配一个就是 dp[i][j-1],匹配多个就是s2[j] == s2[j-1]的时候, 并且dp[i-1][j-1] ,dp[i-1][j] 任意一个是1就行...

都是常规的二维DP....当时卡签到题, 心态有点炸把..也是DP素养不够,DP做了一大堆水题, 没怎么练, 找个机会狂练DP了把

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>using namespace std;const int maxn = 3e3 + 5;int dp[maxn][maxn];char s1[maxn], s2[maxn];int main(){    int t;    cin >> t;    while(t--)    {        memset(dp, 0, sizeof(dp));        scanf(" %s", s1+1);        scanf(" %s", s2+1);        int len1 = strlen(s1+1);        int len2 = strlen(s2+1);        dp[0][0] = 1;        if(s2[2] == '*') dp[0][2] = 1;//        cout << s1[len1-1] << endl;        for(int i = 1; i <= len1; i++)        {            for(int j = 1; j <= len2; j++)            {                if(s1[i] == s2[j] || s2[j] == '.')                    dp[i][j] = dp[i-1][j-1];                if(s2[j] == '*')                {                    dp[i][j] = dp[i][j-2] | dp[i][j-1];                    if((dp[i-1][j-1] || dp[i-1][j]) && s1[i] == s1[i-1])                        dp[i][j] = 1;                }            }        }        puts(dp[len1][len2] ? "yes" : "no");    }    return 0;}


原创粉丝点击