f(i,j)=max(f(i-1,j-1),f(i-1,j),f(i,j-1),f(i-1,j-1)+1)
虽然f(i-1,j)与f(i,j-1)有交集但并不影响最大值
f(i,j)=max(f(i-1,j),f(i,j-1),f(i-1,j-1)+1)
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1010;
int n;
char a[N],b[N];
int f[N][N];//f(i,j)为a[1~i]b[1~j]的所有公共子序列的最大值
int main()
{
cin>>n>>a+1>>b+1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
f[i][j]=f[i-1][j];
f[i][j]=max(f[i][j],f[i][j-1]);
if(a[i]==b[j])
f[i][j]=max(f[i][j],f[i-1][j-1]+1);
}
}
cout<<f[n][n]<<endl;
return 0;
}