#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
using namespace std;
#define maxn 1005
int ans[maxn][maxn];
int mark[maxn][maxn];
string s1, s2;
void printLCS(int i,int j) {
if(i == 0 && j == 0)
return ;
if(mark[i][j] == 0) {
printLCS(i-1,j-1);
cout << s1[i-1];
} else if(mark[i][j] == 1) { //根据回溯的位置进行输出
printLCS(i-1,j);
cout << s1[i-1];
} else {
printLCS(i,j-1);
cout << s2[j-1];
}
}
int longestCommonSubsequence(string A, string B) {
int m = A.size();
int n = B.size();
for(int i = 0; i <= m; ++i) {
ans[i][0] = 0;
mark[i][0] = 1;//1:用A[i-1]添加
}
for(int j = 0; j <= n; ++j) {
ans[0][j] = 0;
mark[0][j] = -1;//-1: 用B[j-1]添加
}
for(int i = 1; i <= m; ++i) {
for(int j = 1; j <= n; ++j) {
if(A[i-1] == B[j-1]) {
ans[i][j] = ans[i-1][j-1] + 1;
mark[i][j] = 0;//A[i-1]、B[j-1]都可以添加
} else {
if(ans[i-1][j] > ans[i][j-1]) {
ans[i][j] = ans[i-1][j];
mark[i][j] = 1;//1:用A[i-1]添加
} else {
ans[i][j] = ans[i][j-1];
mark[i][j] = -1;//-1: 用B[j-1]添加
}
}
}
}
return ans[m][n];
}
int main() {
//freopen("data.in","r",stdin);
ios::sync_with_stdio(false);
while(cin >> s1 >> s2 ) {
int res = longestCommonSubsequence(s1, s2);
printLCS(s1.length(), s2.length());
cout << endl;
}
return 0;
}
HDU 1503 Advanced Fruits(LCS)
最新推荐文章于 2019-01-08 01:49:44 发布