今天被一个题磨了一个下午,话不多说先看题
http://acm.hdu.edu.cn/showproblem.php?pid=1501
**********************************************************************************************************************************************************************************************************************
不翻译了,比较简单。。。。
**********************************************************************************************************************************************************************************************************************
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".
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.
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.


1 include<iostream> 2 #include<cstring> 3 using namespace std; 4 int vis[201][201]; 5 string str1,str2,str3; 6 int dfs(int i1,int i2,int p){ 7 if(p==str3.length()){ 8 return 1; 9 } 10 11 if(vis[i1][i2]||str1[i1]==str3[p]&&dfs(i1+1,i2,p+1)){ 12 vis[i1][i2]=1; 13 return 1; 14 } 15 if(vis[i1][i2]||str2[i2]==str3[p]&&dfs(i1,i2+1,p+1)){ 16 vis[i1][i2]=1; 17 return 1; 18 } 19 20 return 0; 21 22 } 23 int main(){ 24 int T,i=1; 25 cin>>T; 26 while(T--){ 27 cin>>str1>>str2>>str3; 28 memset(vis,0,sizeof(vis)); 29 30 if(dfs(0,0,0)) 31 cout<<"Data set "<<i<<": yes"<<endl; 32 else 33 cout<<"Data set "<<i<<": no"<<endl; 34 i++; 35 } 36 }
这是ac的


1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 int vis[201][201]; 5 string str1,str2,str3; 6 int dfs(int i1,int i2,int p){ 7 if(p==str3.length()){ 8 return 1; 9 } 10 if( !vis[i1][i2] ) return 0; 11 12 vis[i1][i2]=0; 13 14 if(vis[i1][i2] ==1 ||str1[i1]==str3[p]&&dfs(i1+1,i2,p+1)){ 15 vis[i1][i2]=1; 16 return 1; 17 } 18 19 if(str2[i2]==str3[p]&&dfs(i1,i2+1,p+1)){ 20 vis[i1][i2]=1; 21 return 1; 22 } 23 24 return 0; 25 26 } 27 int main(){ 28 int T,i=1; 29 cin>>T; 30 while(T--){ 31 cin>>str1>>str2>>str3; 32 memset(vis,-1,sizeof(vis)); 33 34 if(dfs(0,0,0)) 35 cout<<"Data set "<<i<<": yes"<<endl; 36 else 37 cout<<"Data set "<<i<<": no"<<endl; 38 i++; 39 } 40 }
主要区别是TLE的代码的标志数组vis[i][j]只能判断在i与j情况下可行;
而ac的代码可以判定在i与j情况下可行或不可行;这样的剪枝才有效(可行的情况只是少部分)。。。