题目大意:求两个字符串a,b的最大公共子序列,子序列定义为可不连续但顺序不乱
思路:动态规划,dp[i][j]表示a[0……i-1]和b[0……j-1]的LCS,枚举最后一个字母即a[i-1]和b[j-1],如果a[i-1] == b[j-1],则dp[i][j] = dp[i-1][j-1] + 1; 如果不相等,则dp[i][j] = max(dp[i-1][j],dp[i][j-1])...不过这样空间复杂度有点高,一维dp 可以降低空间复杂度,以后学习!
#include <cstdio>
#include <string>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <iostream>
#include <iomanip>
using namespace std;
#define maxn 1005
#define MOD 1000000007
#define mem(a) memset(a , 0 , sizeof(a))
#define LL __int64
#define INF 999999999
int n ;
int dp[maxn][maxn];
char a[maxn] , b[maxn];
int main()
{
int n;
int k = 0;
while(scanf("%s %s" , a , b) != EOF)
{
int len1 = strlen(a);
int len2 = strlen(b);
// mem(dp);
for(int i = 0 ; i < len1 ; i ++) dp[i][0] = 0;
for(int i = 0 ; i < len2 ; i ++) dp[0][i] = 0;
for(int i = 1 ; i <= len1 ; i ++)
{
for(int j = 1 ; j <= len2 ; j ++)
{
if(a[i-1] == b[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
else if(dp[i-1][j] >= dp[i][j-1]) dp[i][j] = dp[i-1][j];
else dp[i][j] = dp[i][j-1];
}
}
printf("%d\n" , dp[len1][len2]);
}
return 0;
}