poj 2192 Zipper

题意:             给定三个字符串,判断前两个经过字符顺序不变的组合能否变为第三个字符串。            用bool型数组dp[i][j]记录str1的前i个字符和str2的前j个字符能否组合成str3的前i+j个字符。str3的最后一个字符肯定是 str1或str2的最后一个字符,想得到dp[i][j],则必须知道dp[i-1][j](str1的前i-1个字符和str2的前j个字符能否组合成str3的前i-1+j个字符)和dp[i][j-1]str1的前i个字符和str2的前j-1个字符能否组合成str3的前i+j-1个字符),由此将问题分解为str1的前n个字符和str2的前m个字符能否组合成str3的前n+m个字符。最后的s[1][0],s[0][1]可直接得到。dp[str1_len][str2_len],便是最后所求。


代码:

#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std ;
int main(){
    bool dp[300][300] ;
    char str1[300], str2[300], str3[600] ;
    int n, m = 0 ;
    cin >> n ;
    while(n--){
        getchar() ;
        cin >> str1+1 >> str2+1 >> str3+1 ;
        int s1 = strlen(str1+1) ;
        int s2 = strlen(str2+1) ;
        dp[0][0] = true ;
        for(int i=1; i<=s1; i++)            //找出str1从字符串开头与str3连续相同的字符
            if(dp[i-1][0]&&str1[i]==str3[i])
                dp[i][0] = true ;
            else
                dp[i][0] = false ;
        for(int i=1; i<=s2; i++)            //找出str2从字符串开头与str3连续相同的字符
            if(dp[0][i-1]&&str2[i]==str3[i])
                dp[0][i] = true ;
            else
                dp[0][i] = false ;
        for(int i=1; i<=s1; i++)
            for(int j=1; j<=s2; j++)
                if(dp[i-1][j]&&str1[i]==str3[i+j]||dp[i][j-1]&&str2[j]==str3[i+j])
//这里有两种情况可判断s[i][j]是否可行
      dp[i][j] = true ;
                else
                    dp[i][j] = false ;
        m ++ ;
        cout <<"Data set " << m << "" ;
        if(dp[s1][s2])
            cout << "yes" << endl ;
        else
            cout << "no" << endl ;
    }
    return 0 ;

} 

原文地址:https://www.cnblogs.com/xiaolongchase/p/2137832.html