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".
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.
3
cat tree tcraete
cat tree catrtee
cat tree cttaree
Data set 1: yes
Data set 2: yes
Data set 3: no
题意:给你3个单词,要你判断第三个单词是否由前2个单词以任意的排列(这2个单词的顺序不能改变)组合而成
思路:数据太小了,直接DFS吧!用a,b分别表示2个单词出现到了哪个字母,如果最终能出现完这2个单词,那么说明是满足条件的
AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char str1[205];
char str2[205];
char str[405];
int vis[205][205];
int len1,len2,len;
int flag;
void dfs(int a,int b,int l)
{
if(vis[a][b])
return ;
if(a==len1&&b==len2)
{
flag=1;
}
if(flag==1)
return ;
vis[a][b]=1;
if(str[l]==str1[a]&&a<len1)
{
a++;
dfs(a,b,l+1);
a--;
}
if(str[l]==str2[b]&&b<len2)
{
b++;
dfs(a,b,l+1);
}
}
int main()
{
int t;
scanf("%d",&t);
for(int j=1;j<=t;j++)
{
getchar();
scanf("%s%s%s",str1,str2,str);
memset(vis,0,sizeof(vis));
int i;
flag=0;
len1=strlen(str1);
len2=strlen(str2);
dfs(0,0,0);
if(flag)
printf("Data set %d: yes\n",j);
else
printf("Data set %d: no\n",j);
}
return 0;
}