#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
vector<string> str1;
vector<string> str2;
const int maxn = 500+5;
int dp[maxn][maxn];
int road[maxn][maxn];
vector<string> ans;
void LCS() {
memset(dp, 0, sizeof(dp));
for(int i = 0; i <= str1.size(); i++) {
dp[i][0] = 0;
}
for(int j = 0; j <= str2.size(); j++) {
dp[0][j] = 0;
}
for(int i = 1; i <= str1.size(); ++i) {
for(int j = 1; j <= str2.size(); ++j) {
if(str1[i-1] == str2[j-1]) {//公共字符
dp[i][j] = dp[i-1][j-1] + 1;
road[i][j] = 0;
} else {
if(dp[i-1][j] > dp[i][j-1]) {//str1的长
dp[i][j] = dp[i-1][j];
road[i][j] = 1;
} else {//str2的长
dp[i][j] = dp[i][j-1];
road[i][j] = -1;
}
}
}
}
}
void calPath(int n1, int n2) {
if(n1 == 0 && n2 == 0)
return;
if(road[n1][n2] == 0) {
calPath(n1-1, n2-1);
ans.push_back(str1[n1-1]);
}
if(road[n1][n2] == 1) {
calPath(n1-1, n2);
}
if(road[n1][n2] == -1) {
calPath(n1, n2-1);
}
}
int main(void) {
//freopen("data.in", "r", stdin);
//ios::sync_with_stdio(false);
string str;
while(cin >> str) {
if(str != "#") {
str1.push_back(str);
while(cin >> str && str != "#") {
str1.push_back(str);
}
}
while(cin >> str && str != "#") {
str2.push_back(str);
}
LCS();
calPath(str1.size(), str2.size());
if(ans.size() > 0) {
for(int i = 0; i < ans.size(); ++i) {
cout << ans[i];
if( i != ans.size()-1)
cout << " ";
}
}
cout << endl;
}
return 0;
}
POJ2250:Compromise(LCS)
猜你喜欢
转载自blog.csdn.net/ccshijtgc/article/details/80964931
今日推荐
周排行