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".
InputThe 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.
OutputFor 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
题意:给出a、b、c三个字符串,c的长度是a+b的长度,在a、b原先顺序不变的情况下,问是否能拼出c
思路:原以为是字符串匹配问题,结果是深搜。。
因为给出的a、b两个字符串的长度刚好等于第三个字符串的长度,所以可以dfs。所以当长度满足或者该字符已经用过就可以进行return。
搜索传入的是三个字符串的下标,根据下标进行判断。
最后跳出的条件就是c串的最后的一个字符要么是a串的最后一个字符,要么是b串的最后一个字符。
#include
#include
#include
#include
#define inf 0x3f3f3f3f
using namespace std;
//3
//cat tree tcraete
//cat tree catrtee
//cat tree cttaree
//out
//Data set 1: yes
//Data set 2: yes
//Data set 3: no
string s1,s2,s3;
int ls1,ls2,ls3;
int flag;
int book[][];
void dfs(int x,int y,int z)//传入下标
{
if(z==ls3)//长度找到之后
{
flag=;
return;
}
if(flag==||book[x][y]==)//已经找到了或者该字符已经用过了
return;
book[x][y]=;
if(x
int t=;
while(n--)
{
s1.erase();
s2.erase();
s3.erase();
memset(book,,sizeof(book));
cin>>s1>>s2>>s3;
ls1=s1.length();
ls2=s2.length();
ls3=s3.length();
flag=;
dfs(,,);
if(flag)
cout<<"Data set "<<dec<<t++<<": yes"<<endl;
else
cout<<"Data set "<<dec<<t++<<": no"<<endl;
}
return ;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章