最长公共子序列,其实就是最长上升子序列的变形。 dp[i][j]表示以第一个序列的i位置为结尾和以第二个序列的j位置为结尾的子序列的公共子序列的长度。
显然影响决策的因素就是这两个序列的位置,所以二重循环直接搞就行了,如果这两个位置的字符相同就+1
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
char s1[10000],s2[10000],s[10000];
int d[999][999];
int main(){
while(~scanf("%s",s1)){
memset(d,0,sizeof(d));
scanf("%s",s2);
int n = strlen(s1),m=strlen(s2);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(s1[i-1]==s2[j-1]) d[i][j] = d[i-1][j-1] + 1;
else d[i][j] = max(d[i-1][j],d[i][j-1]);
}
}
printf("%d\n",d[n][m]);
}
return 0;
}