动态规划练习 7

题目:Compromise (POJ 2250)

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

#include 
#include 
#include 
#include 
#include 
#include 
 
using namespace std;
 
int len[100][100];
 
void lcs(vector &result, const vector &a, const vector &b)
{
    for (size_t i = 1; i <= a.size(); ++i)
    {
        for (size_t j = 1; j <= b.size(); ++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]);
            }
        }
    }
 
    size_t i = a.size();
    size_t j = b.size();
 
    while (i > 0 && j > 0)
    {
        if (len[i][j] == len[i - 1][j])
        {
            --i;
        }
        else if (len[i][j] == len[i][j - 1])
        {
            --j;
        }
        else
        {
            result.insert(result.begin(), a[i - 1]);
            --i; --j;
        }
    }
}
 
int main(int argc, char **argv)
{
    vector txt[2];
    string word;
    int sep_count = 0;
 
    memset(len, 0, sizeof(len));
 
    while (cin >> word)
    {
        if (word == "#" && ++sep_count % 2 == 0)
        {
            vector result;
 
            lcs(result, txt[0], txt[1]);
            copy(result.begin(), result.end(), ostream_iterator(cout, " "));
            cout << endl;
 
            txt[0].clear();
            txt[1].clear();
        }
 
        if (word != "#")
        {
            txt[sep_count % 2].push_back(word);
        }
    }
 
    return 0;
}

转载于:https://www.cnblogs.com/codingmylife/archive/2012/08/05/2624064.html

你可能感兴趣的:(动态规划练习 7)