Hdu-1501 Zipper(记忆化搜索)

本文介绍了一种使用记忆化搜索解决串匹配问题的方法,通过给定的三个字符串,判断第三个字符串是否能由前两个字符串按原顺序组合而成。文章详细解释了算法思路,并提供了完整的C++代码实现。

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

Problem Description
Given three strings, you are to determine whether the third string can be formed by combining the characters in the first two strings. The first two strings can be mixed arbitrarily, but each must stay in its original order.

For example, consider forming “tcraete” from “cat” and “tree”:

String A: cat
String B: tree
String C: tcraete

As you can see, we can form the third string by alternating characters from the two strings. As a second example, consider forming “catrtee” from “cat” and “tree”:

String A: cat
String B: tree
String C: catrtee

Finally, notice that it is impossible to form “cttaree” from “cat” and “tree”.

Input
The first line of input contains a single positive integer from 1 through 1000. It represents the number of data sets to follow. The processing for each data set is identical. The data sets appear on the following lines, one data set per line.

For each data set, the line of input consists of three strings, separated by a single space. All strings are composed of upper and lower case letters only. The length of the third string is always the sum of the lengths of the first two strings. The first two strings will have lengths between 1 and 200 characters, inclusive.

Output
For each data set, print:

Data set n: yes

if the third string can be formed from the first two, or

Data set n: no

if it cannot. Of course n should be replaced by the data set number. See the sample output below for an example.

Sample Input
3
cat tree tcraete
cat tree catrtee
cat tree cttaree

Sample Output
Data set 1: yes
Data set 2: yes
Data set 3: no

题意:给三个串,问第三个串能不能由前两个串组成,并且单个字符串的顺序不变。

思路:简单记忆化搜索。
(刚开始想歪了,想先判断这俩串和第三个串的字母数量是不是一样,然后用两次最长公共子序列做,我觉得这么做可能会超时,但是没想到wa了,,到现在也不知道为什么,感觉这种思路也ok啊。。就是麻烦点)

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int f[210][210];
int la,lb,lc;
string s1,s2,s3;
int dfs(int i,int j,int k)
{
	if(i>=la&&j>=lb)
	{	
		if(k>=lc)
			return 1;
		return 0;
	}
	if(f[i][j]!=-1)
		return f[i][j];	
	int ans=0;
	if(s1[i]==s3[k]&&i<la)
		ans=max(ans,dfs(i+1,j,k+1));
	if(s2[j]==s3[k]&&j<lb)
		ans=max(ans,dfs(i,j+1,k+1));
	return f[i][j]=ans;
}
int main()
{
	int t,cas=1;
	cin>>t;
	while(t--)
	{		
		cin>>s1>>s2>>s3;
		la=s1.size(),lb=s2.size(),lc=s3.size();
		printf("Data set %d: ",cas++);
		memset(f,-1,sizeof f);
		if(dfs(0,0,0)<=0)
			printf("no\n");
		else
			printf("yes\n");
	}
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值