题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1159
题意:给了两个字符串,求最大公共子序列的长度
分析:裸的LCS题目,dp[i][j]表示第一个字符串前i个字符和第二个字符串前j个字符最长公共子序列的长度。如果第i个字符和第j个字符相同,它们的最长公共子序列的长度为前i-1个字符和前j-1个字符的最长公共子序列的长度加一,否则取dp[i-1][j]和dp[i][j-1]的最大值。
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;
const int maxn = 1e3 + 10;
typedef long long ll;
char s1[maxn],s2[maxn];
int dp[maxn][maxn];
void work(int len1,int len2)
{
for(int i = 1; i <= len1; i++)
{
for(int j = 1; j <= len2; j++)
{
if(s1[i - 1] == s2[j - 1])
{
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else
{
dp[i][j] = max(dp[i - 1][j],dp[i][j - 1]);
}
}
}
}
int main()
{
int n,len1,len2;
while(~scanf("%s%s",s1,s2))
{
memset(dp,0,sizeof(dp));
len1 = strlen(s1);
len2 = strlen(s2);
work(len1,len2);
printf("%d\n",dp[len1][len2]);
}
return 0;
}