Zipper(深搜+记忆化)

该博客探讨了一种使用深度优先搜索(DFS)结合记忆化搜索的方法来判断第三个字符串是否能由前两个字符串按顺序交替组成。通过示例解释了算法的工作原理,并提供了AC代码实现。代码中,当遇到已计算过的状态时,利用记忆化搜索避免重复计算,从而提高了效率。若第三个字符串长度不等于前两个字符串长度之和,则直接判断不能形成。该问题主要涉及字符串处理和算法优化。

Zipper (深搜+记忆化)

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

题意: 给你三个字符串,问你第三个字符串是不是由前两个演变而来的,是就输出yes,否则输出no,原字符串的顺序不能改变

思路: 深搜+记忆化,不然会超时,注意,前两个字符串的长度一定是等于第三个字符串长度的,否则一定不能演变成第三个字符串

AC代码:

#include<stdio.h>
#include<string.h>
char a[1100],b[1100],c[1100];
int book[1100][1100];
int k1,k2,k3,f,aa;
void dfs(int aa,int bb,int cc)
{
	if(k3==cc)
	{
		f=1;
		return ;
	}
	if(book[aa][bb])//记忆化搜索 
	return;
	book[aa][bb]=1;
	if(a[aa]==c[cc])
	dfs(aa+1,bb,cc+1);
	if(b[bb]==c[cc])
	dfs(aa,bb+1,cc+1);
}
int main()
{
	int t,i,j,d=1;
	scanf("%d",&t);
	while(t--)
	{
		memset(book,0,sizeof(book));
		scanf("%s",a);
		scanf("%s",b);
		scanf("%s",c);
		k1=strlen(a);
		k2=strlen(b);
		k3=strlen(c);
		if(k1+k2!=k3)
		{
			printf("Data set %d: no\n",d++);
			continue;
		}
		f=0;
		dfs(0,0,0);
		if(f)
			printf("Data set %d: yes\n",d++);
		else
			printf("Data set %d: no\n",d++);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值