HDOJ topic 1501 Zipper (DFS)
ZipperTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission (s): 7223 Accepted Submission (s): 2576
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 shocould be replaced by the data set number. See the sample output below for an example.
Sample Input
3cat tree tcraetecat tree catrteecat tree cttaree
Sample Output
Data set 1: yesData set 2: yesData set 3: no
Source Pacific Northwest 2004
Recommend linle | We have carefully selected several similar problems for you: 1502 1227 1158 1080 ac code
#include
#include
char a[220],b[220],c[220*2];bool flag;int len1,len2,len3;void dfs(int x,int y,int len){if(flag)return;if(len>=len3){flag=true;return;}if(a[x]==c[len]){dfs(x+1,y,len+1);}if(b[y]==c[len])dfs(x,y+1,len+1);}int main(){int t,cot=0;scanf("%d",&t);while(t--){scanf("%s%s%s",a,b,c);len1=strlen(a);len2=strlen(b);len3=strlen(c);if(len1+len2!=len3){printf("Data set %d: no\n",++cot);continue;}flag=false;if(a[len1-1]==c[len3-1]||b[len2-1]==c[len3-1]){dfs(0,0,0);}if(flag)printf("Data set %d: yes\n",++cot);elseprintf("Data set %d: no\n",++cot);}}