zipper poj2192 dp on string

The meaning of the question: Give you three strings, ask if you can synthesize the third from the first two, and ask to not change the order of the first two strings. The question guarantees that the length of the third string is the sum of the lengths of the first two strings.

 

Solution: This question can be passed with violence and deep search (the data is too watery). The solution of DP is given here.

dp[i][j] (bool type) indicates whether the first i characters of the first string and the first j characters of the second string can be combined into the first i+j strings of the third string.

Then the state transition equation is:

1 if(dp[i-1][j]&&s1[i]==sum[i+j]||dp[i][j-1]&&s2[j]==sum[i+j])
2                 dp[i][j]=true;

For the interpretation of the equation of state:

1. If the first i-1 characters of the first string and the first j characters of the second string can be combined into the first i+j-1 characters of the third string, then if the first string is The i-th character is the same as the i+j-th character of the third character, then the first i of the first string plus the first j characters of the second string can be combined into the first i of the third string +j characters, then dp[i][j] is equal to true, otherwise dp[i][j]=false.

 

2. If the first i characters of the first string and the first j-1 characters of the second string can be synthesized into the first i+j-1 characters of the third string, then if the The jth character is the same as the i+jth character of the third character, then the first i of the first string plus the first j characters of the second string can synthesize the first i of the third string +j characters, then dp[i][j] is equal to true, otherwise dp[i][j]=false. As for the initialization, it is easy to write it out according to the state transition equation.

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxN=205;
char s1[maxN],s2[maxN],sum[maxN+maxN];
bool dp[maxN][maxN];
bool solve(){
    int i,j;
    int len1=strlen(s1+1);
    int len2=strlen(s2+1);
    memset(dp,false,sizeof(dp));
    for(i=1;i<=len1;i++)
        if(s1[i]==sum[i])dp[i][0]=true;
    for(i=1;i<=len2;i++)
        if(s2[i]==sum[i])dp[0][i]=true;
    for(i=1;i<=len1;i++)
        for(j=1;j<=len2;j++)
            if(dp[i-1][j]&&s1[i]==sum[i+j]||dp[i][j-1]&&s2[j]==sum[i+j])
                dp[i][j]=true;
    if(dp[len1][len2])return true;
    return false;
}
intmain()
{
    int T,case=0;
    scanf("%d",&T);
    while(T--){
        scanf("%s %s %s",s1+1,s2+1,sum+1);
        printf("Data set %d: ",++cas);
        if(solve())printf("yes\n");
        else       printf("no\n");
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324764518&siteId=291194637