[恢]hdu 1159
2011-12-17 07:19:48
地址:http://acm.hdu.edu.cn/showproblem.php?pid=1159
题意:求两个字符串的最长公共字串(LCS)。
mark:经典dp。dp[i][j]表示a的前i个字符和j的前i个字符的LCS长度。有dp[i][j] = max(dp[i-1][j-1]+(a[i]==b[j]), dp[i-1][j], dp[i][j-1])。
代码:
# include <stdio.h>
# include <string.h>
int dp[1010][1010] ;
char s1[1010], s2[1010] ;
int max(int a, int b){return a>b?a:b;}
int min(int a, int b){return a<b?a:b;}
int lcs(char a[], char b[])
{
int i, j, len1 = strlen(a), len2 = strlen(b) ;
memset (dp, 0, sizeof(dp)) ;
dp[0][0] = (a[0] == b[0]) ;
for (i = 1 ; i < len1 ; i++)
dp[i][0] = max(dp[i-1][0], a[i]==b[0]) ;
for (j = 1 ; j < len2 ; j++)
dp[0][j] = max(dp[0][j-1], a[0]==b[j]) ;
for (i = 1 ; i < len1 ; i++)
for(j = 1 ; j < len2 ; j++)
dp[i][j] = max(
dp[i-1][j-1]+(a[i]==b[j]),
max(dp[i-1][j], dp[i][j-1])) ;
return dp[len1-1][len2-1] ;
}
int main ()
{
while (~scanf ("%s %s%*c", s1, s2))
printf ("%d\n", lcs(s1, s2)) ;
return 0 ;
}