2013
12-11

# Zipper

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.

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.

3
cat tree tcraete
cat tree catrtee
cat tree cttaree

Data set 1: yes
Data set 2: yes
Data set 3: no

DP解法：

C去除除最后一位，就变成是否可以求出 A-1和B 或者 A与B-1 与 是否可以构成 C-1。。。

dp[i][j]= (dp[i-1][j]&&(a[i]==c[i+j]))||(dp[i][j-1]&&(b[j]==c[i+j]))

#include<stdio.h>
#include<string.h>

char a[201],b[201],c[402];
int la,lb,lc;
int dp[201][201];

int main()
{
int ncase;
scanf("%d",&ncase);
for(int n=1; n<=ncase; n++) {

a[0]='p';
b[0]='p';
c[0]='p';

scanf("%s%s%s",a+1,b+1,c+1);

la=strlen(a);
lb=strlen(b);
lc=strlen(c);

la-=1;
lb-=1;

//处理边界
for (int i=1; i<=la; i++)
if (a[i]==c[i]) dp[i][0]=1;

for (int i=1; i<=lb; i++)
if (b[i]==c[i]) dp[0][i]=1;
//DP
for (int i=1; i<=la; i++)
for (int j=1; j<=lb; j++)
dp[i][j]= (dp[i-1][j]&&(a[i]==c[i+j]))||(dp[i][j-1]&&(b[j]==c[i+j]));

printf("Data set %d: ",n);
if (dp[la][lb]==1) printf("yes\n");
else printf("no\n");

}
}
a

1. 算法是程序的灵魂，算法分简单和复杂，如果不搞大数据类，程序员了解一下简单点的算法也是可以的，但是会算法的一定要会编程才行，程序员不一定要会算法，利于自己项目需要的可以简单了解。