https://vjudge.net/problem/POJ-1458
求最长公共子序列。。这是一个经典问题了,也记得去年看了这个看了好久qwq,
子序列,不一定是相连的qwq。
我的理解是,公共串在两个串中 的最后出现位置是不同的,
总共两种状态,可以递推qwq
#include <cstdio>
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
/*最长公共子序列
*/
const int maxn=1005;
char a[maxn];
char b[maxn];
int dp[maxn][maxn];
int len1,len2;
void out(){
stack<char>s;
int l1=len1;int l2=len2;
//cout<<l1<<endl;
while(l1>0&&l2>0){
//cout<<l1<<" "<<l2<<endl;
if(a[l1]==b[l2]){
s.push(a[l1]);
//cout<<a[l1]<<endl;
l1--;l2--;
}
else if(dp[l1][l2-1]>dp[l1-1][l2])
{ //cout<<b[l2]<<endl;
l2--;}
else
{ //cout<<a[l1]<<endl;
l1--;}
}
while(!s.empty()){
cout<<s.top();
s.pop();
}
cout<<endl;
}
int main()
{ int t;
while(~scanf("%s %s",a+1,b+1)){
//cout<<a<<endl;
a[0]='0';b[0]='0';
len1=strlen(a+1);
len2=strlen(b+1);//len2++;
memset(dp,0,sizeof(dp));
//cout<<len1<<len2<<endl;
int max1=-1;
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(a[i]==b[j])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
max1=max(dp[i][j],max1);
}
}
printf("%d\n",max1);
out();
}
return 0;
}