动态规划练习 10

题目:Zipper (POJ 2192)

链接:http://acm.pku.edu.cn/JudgeOnline/problem?id=2192

#include <iostream>
#include <string>
#include <memory.h>
 
using namespace std;
 
bool dp[201][201];
 
// Recursion version.
bool check_yes(const string &a, size_t i, const string &b, size_t j, const string &c, size_t k)
{
    if (k >= c.size())
    {
        return true;
    }
 
    bool ret1 = false, ret2 = false;
 
    if (i < a.size() && c[k] == a[i])
    {
        ret1 = check_yes(a, i + 1, b, j, c, k + 1);
    }
 
    if (j < b.size() && c[k] == b[j])
    {
        ret2 = check_yes(a, i, b, j + 1, c, k + 1);
    }
 
    return ret1 || ret2;
}
 
int main(int argc, char **argv)
{
    int n;
    string a, b, c;
 
    cin >> n;
 
    for (int m = 1; m <= n; ++m)
    {
        cin >> a >> b >> c;
 
        // Recursion version.
        // cout << check_yes(a, 0, b, 0, c, 0) << endl;
        // dp[i][j] = (dp[i - 1][j] && a[i - 1] == c[i + j - 1]) || 
        //            (dp[i][j - 1] && b[j - 1] == c[i + j - 1]);
 
        memset(dp, 0, sizeof(dp));
 
        dp[0][0] = true;
 
        for (size_t i = 1; i <= a.size(); ++i)
        {
            dp[i][0] = dp[i - 1][0] && a[i - 1] == c[i - 1];
        }
 
        for (size_t j = 1; j <= b.size(); ++j)
        {
            dp[0][j] = dp[0][j - 1] && b[j - 1] == c[j - 1];
        }
 
        for (size_t i = 1; i <= a.size(); ++i)
        {
            for (size_t j = 1; j <= b.size(); ++j)
            {
                dp[i][j] = (dp[i - 1][j] && a[i - 1] == c[i + j - 1])
                        || (dp[i][j - 1] && b[j - 1] == c[i + j - 1]);
            }
        }
 
        cout << "Data set " << m << ": " << 
            (dp[a.size()][b.size()] ? "yes" : "no") << endl;
    }
 
    return 0;
}
posted @ 2012-08-11 18:01  紫红的泪  阅读(193)  评论(0编辑  收藏  举报