动态规划练习 7
题目:Compromise (POJ 2250)
链接:http://acm.pku.edu.cn/JudgeOnline/problem?id=2250
#include <iostream>
#include <string>
#include <vector>
#include <memory.h>
#include <algorithm>
#include <iterator>
using namespace std;
int len[100][100];
void lcs(vector<string> &result, const vector<string> &a, const vector<string> &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<string> txt[2];
string word;
int sep_count = 0;
memset(len, 0, sizeof(len));
while (cin >> word)
{
if (word == "#" && ++sep_count % 2 == 0)
{
vector<string> result;
lcs(result, txt[0], txt[1]);
copy(result.begin(), result.end(), ostream_iterator<string>(cout, " "));
cout << endl;
txt[0].clear();
txt[1].clear();
}
if (word != "#")
{
txt[sep_count % 2].push_back(word);
}
}
return 0;
}