Combine String HDU - 5707 (简单dp)

Combine String HDU - 5707 (简单dp)

题目链接
题目大意:给定三个字符串,str1, str2, str,问不改变 str1, str2串中字母在原串中的相对位置,能否变成str
input:
abc def adebcf
abc def abecdf
output:Yes No
当初想这个题啊,根本没往dp方面想,后来看了题解耳目一新。
一开始做的也不对,dp[i][j]来表示str1串中用i个,str2串中用j个最多能凑出str串中几个,后来发现,如果dp[5][0]是0,dp[7][0]也应该是0,但是我的做法,如果str[6] = str1[6],它就会等于1。看到题解,发现他们是一个与的关系,而不是简单的相加。

#include <bits/stdc++.h>
using namespace std;

const int maxn = 2e3 + 100;

bool dp[maxn][maxn];
char str[maxn], str1[maxn], str2[maxn];

int main()
{
    while(~scanf("%s %s %s", str1, str2, str)) {
        int len1 = strlen(str1), len2 = strlen(str2), len = strlen(str);

        if(len1 + len2 != len) {
            printf("No\n");
            continue;
        }
        memset(dp, false, sizeof(dp));

        dp[0][0] = 1;
        for(int i = 0; i <= len1; i++) {
            for(int j = 0; j <= len2; j++) {

                 if(i - 1 >= 0)
                 dp[i][j] |= (dp[i - 1][j] && (str1[i - 1] == str[i - 1 + j]));
                 if(j - 1 >= 0)
                 dp[i][j] |= (dp[i][j - 1] && (str2[j - 1] == str[i + j - 1]));
            }

        }

        if(dp[len1][len2]) printf("Yes\n");
        else printf("No\n");
    }
}

猜你喜欢

转载自blog.csdn.net/deerly_/article/details/80356411