首页 > 代码库 > Zipper_DP

Zipper_DP

 

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

3cat tree tcraetecat tree catrteecat tree cttaree

Sample Output

Data set 1: yesData set 2: yesData set 3: no

 

 

 【题意】给出三个字符串,求前两个是否包含在第三个中。

【思路】之前用过dfs,这次用dp,检验dp[len1][len2]是否为1;

#include<iostream>#include<stdio.h>#include<string.h>using namespace std;const int N=555;int dp[N][N];int main(){    int n;    char a[N],b[N],c[N];    int cas=0;    while(~scanf("%d",&n))    {        cas++;        memset( dp,0,sizeof(dp));        scanf("%s%s%s",a+1,b+1,c+1);        int len1=strlen(a+1);        int len2=strlen(b+1);        int len3=strlen(c+1);        for(int i=1;i<=len1;i++)        {            if(a[i]==c[i]) dp[i][0]=1;            else break;        }        for(int j=1;j<=len2;j++)        {            if(b[j]==c[j])                dp[0][j]=1;            else break;        }        for(int i=1;i<=len1;i++)        {            for(int j=1;j<=len2;j++)            {                if(c[i+j]==a[i]&&dp[i-1][j])                    dp[i][j]=1;                if(c[i+j]==b[j]&&dp[i][j-1])                    dp[i][j]=1;            }        }        printf("Data set %d: ",cas);        if(dp[len1][len2]) printf("yes\n");        else printf("no\n");    }    return 0;}

 

Zipper_DP