基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
给出两个字符串A B,求A与B的最长公共子序列(子序列不要求是连续的)。
比如两个串为:
abcicba
abdkscab
ab是两个串的子序列,abc也是,abca也是,其中abca是这两个字符串最长的子序列。
Input
第1行:字符串A 第2行:字符串B (A,B的长度 <= 1000)
Output
输出最长的子序列,如果有多个,随意输出1个。
Input示例
abcicba abdkscab
Output示例
abca
输出最长公共子序列,把求最长公共子序列的改一下就好了
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
string str1,str2,ans;
int dp[1010][1010];
void longestCommonSubsequence() {
int i,j;
int len1 = str1.length();
int len2 = str2.length();
for( i=0 ; i<=len1 ; i++ )
dp[i][0] = 0;
for( j=0 ; j<=len2 ; j++ )
dp[0][j] = 0;
for( i=1 ; i<=len1 ; i++ ) {
for( j=1 ; j<=len2 ; j++ ) {
if( str1[i-1] == str2[j-1] ){
dp[i][j] = dp[i-1][j-1] + 1;
}else if( dp[i-1][j] >= dp[i][j-1] ){
dp[i][j] = dp[i-1][j];
}else{
dp[i][j] = dp[i][j-1];
}
}
}
i=len1 , j=len2;
while( i && j ){
if( str1[i-1]==str2[j-1] ){
ans += str1[i-1];
i--;
j--;
} else if( dp[i][j]==dp[i-1][j] ){
i--;
}else{
j--;
}
}
}
int main() {
// freopen( "in.txt","r",stdin );
std::ios::sync_with_stdio( false );
while( cin >> str1 >> str2 ) {
ans.clear();
longestCommonSubsequence();
reverse( ans.begin(),ans.end() );
// cout << ans.length() << endl;
cout << ans << endl;
// cout << ans[0] << "*" << ans[1] << "*" << ans[2] << "*" << ans[3] << "*" << endl;
}
}
6683




被折叠的 条评论
为什么被折叠?



