Zipper
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4209 Accepted Submission(s): 1513
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".
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.
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.
3 cat tree tcraete cat tree catrtee cat tree cttaree
Data set 1: yes Data set 2: yes Data set 3: no
#include<stdio.h> char a[201],b[201],c[402]; int visit[201][201]={0}; //剪枝 int isOk=0; void dfs(int i,int j,int k) { if(visit[i][j]==1) return; //剪枝 if(c[k]=='\0') { isOk=1; return; } if(a[i]!='\0'&&c[k]==a[i]) dfs(i+1,j,k+1); if(b[j]!='\0'&&c[k]==b[j]) dfs(i,j+1,k+1); visit[i][j]=1; //剪枝 } int main() { int n,i,j,cnt=0; // int flag=0; // freopen("d:\\data.in.txt","r",stdin); scanf("%d",&n); while(n--) { isOk=0; for(i=0;i<201;i++) //剪枝 for(j=0;j<201;j++) //剪枝 visit[i][j]=0; //剪枝 scanf("%s%s%s",a,b,c); dfs(0,0,0); printf("Data set %d: %s\n",++cnt,isOk?"yes":"no"); } return 0; }
感觉dp应该更快,就写了个dp的程序,结果比dfs还慢,应该是程序样例给的太简单,没有出复杂的数据。
#include<stdio.h> #include<string.h> #define MAXN 204 char a[MAXN],b[MAXN],c[2*MAXN]; int d[MAXN][MAXN]; int main(void) { int T,i,j,t; int d1,d2,d3; t=1; // freopen("d:\\in.txt","r",stdin); scanf("%d",&T); while(T--) { scanf("%s%s%s",a,b,c); d1=strlen(a); d2=strlen(b); for(i=0;i<=d1;i++) for(j=0;j<=d2;j++) d[i][j]=0; d[0][0]=1; for(i=1;i<=d1;i++) { if(a[i-1]==c[i-1]) d[i][0]=1; else break; } for(i=1;i<=d2;i++) { if(b[i-1]==c[i-1]) d[0][i]=1; else break; } for(i=1;i<=d1;i++) for(j=1;j<=d2;j++) { if(d[i][j-1] && b[j-1]==c[i+j-1]) d[i][j]=1; if(d[i-1][j] && a[i-1]==c[i+j-1]) d[i][j]=1; } printf("Data set %d: ",t++); if(d[d1][d2]) printf("yes\n"); else printf("no\n"); } return 0; }