HDU-1501-Zipper

本文介绍了一种字符串匹配问题的解决方法,使用动态规划(DP)和深度优先搜索(DFS)两种算法来判断两个字符串是否能组合成第三个字符串。通过具体代码示例展示了两种方法的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:https://vjudge.net/problem/HDU-1501

题意:

给定3个字符串,在不改变原来顺序上能否用第一个和第二个组成第三个。

思路:

dp。dp[i][j]表示可以用第一个字符串前i位和第二个字符串前j位,组成第三个字符串前i+j位。

两重循环。

考虑每一次ij,当dp[i-1][j]为1 && a[i-1] == c[i+j-1] 时, dp[i][j] = 1;j同理。

DFS。Vis[i][j]记录到达过此种状态不用考虑。

代码:

dp

#include <iostream>
#include <memory.h>
#include <vector>
#include <map>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <queue>
#include <string>
#include <stack>
#include <iterator>
#include <stdlib.h>
#include <time.h>
#include <assert.h>

using namespace std;
typedef long long LL;

const int MAXN = 1000 + 10;
int dp[MAXN][MAXN];

int main()
{
    int t, cnt = 0;
    string a, b, c;
    cin >> t;
    while (t--)
    {
        cin >> a >> b >> c;
        memset(dp, 0, sizeof(dp));
        /*
        for (int i = 1;i <= a.length();i++)
            dp[i][0] = (a[i-1] == c[i-1]);
        for (int i = 1;i <= b.length();i++)
            dp[0][i] = (b[i-1] == c[i-1]);
        */
        if (a[0] == c[0])
            dp[1][0] = 1;
        if (b[0] == c[0])
            dp[0][1] = 1;
        for (int i = 0;i <= a.length();i++)
        {
            for (int j = 0;j <= b.length();j++)
            {
                if (dp[i][j-1] && b[j-1]==c[i+j-1])
                    dp[i][j] = 1;
                if (dp[i-1][j] && a[i-1]==c[i+j-1])
                    dp[i][j] = 1;
            }
        }
        if (dp[a.length()][b.length()])
            printf("Data set %d: yes\n",++cnt);
        else
            printf("Data set %d: no\n",++cnt);
    }

    return 0;
}

 DFS

#include <iostream>
#include <memory.h>
#include <vector>
#include <map>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <queue>
#include <string>
#include <stack>
#include <iterator>
#include <stdlib.h>
#include <time.h>
#include <assert.h>

using namespace std;
typedef long long LL;

const int MAXN = 1000 + 10;
int Vis[MAXN][MAXN];
bool flag = false;
string a, b, c;

void Dfs(int x, int y, int z)
{
    if (z == c.length())
    {
        flag = true;
        return ;
    }
    if (Vis[x][y])
        return;
    Vis[x][y] = 1;
    if (a[x] == c[z])
        Dfs(x+1, y, z+1);
    if (b[y] == c[z])
        Dfs(x, y+1, z+1);
}

int main()
{
    int t, cnt = 0;
    cin >> t;
    while (t--)
    {
        cin >> a >> b >> c;
        memset(Vis, 0, sizeof(Vis));
        flag = false;
        Dfs(0, 0, 0);
        if (flag)
            printf("Data set %d: yes\n",++cnt);
        else
            printf("Data set %d: no\n",++cnt);
    }

    return 0;
}

 

转载于:https://www.cnblogs.com/YDDDD/p/10665123.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值