1458 -- Common Subsequence
给定序列的子序列是给定序列,其中遗漏了一些元素(可能没有)。给定一个序列 X = < x1, x2, ..., xm > 另一个序列 Z = < z1, z2, ..., zk > 是 X 的子序列,如果存在严格递增的序列 < i1, i2, ... ., ik > X 的索引使得对于所有 j = 1,2,...,k, xij = zj。例如,Z = < a, b, f, c > 是 X = < a, b, c, f, b, c > 的子序列,索引序列 < 1, 2, 4, 6 >。给定两个序列 X 和 Y,问题是找到 X 和 Y 的最大长度公共子序列的长度。
令第一个字符串为a,第二个字符串为b,f[i][j]表示到a第i个字母为止和到b第j个字母为止的lcs。
当a[i]==b[j], 则f[i][j]=f[i-1][j-1]+1,即之前的子串的最大公共子序列加上目前相等的这个字母;
当a[i]!=b[j], 则f[i][j]=max(f[i][j-1],f[i-1][j]),即拿a在i之前的子串与目前的b比较、拿b在j之前的子串与目前的a比较。
边界点:若a[1]==b[1],则f[1][1]=1;否则f[1][1]=0。
细节问题:若是记忆化搜索,因为当为0时也需要作为值返回,所以清空数组的时候要用-1.不然会超时QAQ
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f, maxn=205;
string a,b;
int f[maxn][maxn],la,lb;
//int calc(int i,int j){
// if(f[i][j]!=-1) return f[i][j];
// if(i<1||j<1) return f[i][j]=0;
// if(i==1&&j==1){
// if(a[i]!=b[j]) return 0;
// else return 1;
// }
// if(a[i]==b[j]) f[i][j]=calc(i-1,j-1)+1;
// else f[i][j]=max(calc(i,j-1),calc(i-1,j));
// return f[i][j];
//}
int main(){
while(cin>>a>>b){
// memset(f,-1,sizeof(f));
memset(f,0,sizeof(f));
la=a.length(); lb=b.length();
a='0'+a; b='0'+b;
cout<<a<<endl;
for(int i=1;i<=la;++i){
for(int j=1;j<=lb;++j){
if(i==1&&j==1){
if(a[i]!=b[j]) f[1][1]=0;
else f[1][1]=1;
continue;
}
if(a[i]==b[j]) f[i][j]=f[i-1][j-1]+1;
else f[i][j]=max(f[i][j-1],f[i-1][j]);
}
}
cout<<f[la][lb]<<endl;
// cout&