動態規劃練習 6

weixin_34391854發表於2012-08-05

題目:Common Subsequence (POJ 1458)

連結:http://acm.pku.edu.cn/JudgeOnline/problem?id=1458

#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
 
int len[999][999];
 
int main(int argc, char **argv)
{
    string a, b;
 
    for (size_t i = 0; i < 999; ++i)
    {
        len[i][0] = 0;
    }
 
    for (size_t j = 0; j < 999; ++j)
    {
        len[0][j] = 0;
    }
 
    while (cin >> a >> b)
    {
        const size_t height = a.size() + 1;
        const size_t width = b.size() + 1;
 
        for (size_t i = 1; i < height; ++i)
        {
            for (size_t j = 1; j < width; ++j)
            {
                if (a[i - 1] == b[j - 1])
                {
                    len[i][j] = len[i - 1][j - 1] + 1;
                }
                else
                {
                    len[i][j] = max(len[i - 1][j], len[i][j - 1]);
                }
            }
        }
 
        cout << len[height - 1][width - 1] << endl;
    }
 
    return 0;
}

相關文章