HDOJ-1501文字配列問題[文字検索DFS()]

10363 ワード


Zipper
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 3583    Accepted Submission(s): 1283
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
 
 
Source
Pacific Northwest 2004
 
 
Recommend
linle
 
 
 
 杭電Aの百番目の問題!
 
code:
 1 #include<iostream>

 2 using namespace std;

 3 

 4 char data1[202],data2[202],data[404];

 5 int cases;

 6 bool flag;

 7 int length1,length2,length;

 8 

 9 void DFS(int f1,int f2,int f)

10 {

11     if(f==(length-1))

12     {

13         flag=true;

14         printf("Data set %d: yes
",cases); 15 return; 16 } 17 if(data1[f1]!=data[f]&&data2[f2]!=data[f]) 18 return; 19 if(data1[f1]==data[f]) 20 { 21 DFS(f1+1,f2,f+1); 22 if(flag) 23 return; 24 } 25 if(data2[f2]==data[f]) 26 { 27 DFS(f1,f2+1,f+1); 28 if(flag) 29 return; 30 } 31 } 32 33 int main() 34 { 35 int n; 36 while(~scanf("%d",&n)) 37 { 38 cases=0; 39 while(n--) 40 { 41 cases++; 42 flag=false; 43 scanf("%s%s%s",data1,data2,data); 44 length=strlen(data); 45 length1=strlen(data1); 46 length2=strlen(data2); 47 if((!(data[0]==data1[0]||data[0]==data2[0]))||(!(data[length-1]==data1[length1-1]||data[length-1]==data2[length2-1]))) 48 printf("Data set %d: no
",cases); 49 else 50 { 51 DFS(0,0,0); 52 if(!flag) 53 printf("Data set %d: no
",cases); 54 } 55 } 56 } 57 return 0; 58 }