LCS最长公共子序列模板:
状态转移方程为
dp[i][j]=dp[i-1][j-1]+1 if(in[i]==target[i])
=max{dp[i-1][j],dp[i][j-1]} else;
void LCSLength(int m,int n,char *x,char *y,int **c,int **b)
{
int i,j;
for (i = 1; i <= m; i++) c[i][0] = 0;
for (i = 1; i <= n; i++) c[0][i] = 0;
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
{
if (x[i]==y[j]) {
c[i][j]=c[i-1][j-1]+1; b[i][j]=1;} //b[i][j]用于构造最长公共子序列
else if (c[i-1][j]>=c[i][j-1]) {
c[i][j]=c[i-1][j]; b[i][j]=2;}
else { c[i][j]=c[i][j-1]; b[i][j]=3; }
}
}
法二:
memset(dp,0,sizeof(dp));
int len1 = in.size();
int len2 = target.size();
for(i=1;i<=len1;i++) //LCS最长子序列
for(j=1;j<=len2;j++)
{
if(in[i-1]==target[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j] = Max(dp[i-1][j],dp[i][j-1]);
}
答案为dp[len1][len2]
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
#define X 250
int dp[X][X]; //不知多大
int Max(int a,int b)
{
return a>b?a:b;
}
int main()
{
freopen("sum.in","r",stdin);
freopen("sum.out","w",stdout);
string in,target;
int i,j;
while(cin>>in>>target)
{
memset(dp,0,sizeof(dp));
int len1 = in.size();
int len2 = target.size();
for(i=1;i<=len1;i++) //LCS最长公共子序列模板
for(j=1;j<=len2;j++)
{
if(in[i-1]==target[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j] = Max(dp[i-1][j],dp[i][j-1]);
}
cout<<dp[len1][len2]<<endl;
}
return 0;
}