Description
Input
abcfbc abfcab
programming contest
abcd mnp
Output
4
2
0
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
//求两个字符串的最长公共子序列长度
//虽然是 dp 序列水题,但是我第一次做不会,没想到转移方程
代码里写的很清楚了,31ms
1 #include <stdio.h> 2 #include <string.h> 3 4 char a[1005]; 5 char b[1005]; 6 int dp[1005][1005]; 7 8 int max(int x,int y) 9 {return x>y?x:y;} 10 11 int main() 12 { 13 int i,j; 14 while(scanf("%s%s",a,b)!=EOF) 15 { 16 int la=strlen(a),lb=strlen(b); 17 for (i=0;i<=lb;i++) 18 dp[0][i]=0; 19 for (i=0;i<=la;i++) 20 dp[i][0]=0; 21 for (i=1;i<=la;i++) 22 { 23 for (j=1;j<=lb;j++) 24 { 25 if (a[i-1]==b[j-1]) 26 dp[i][j]=dp[i-1][j-1]+1; 27 else 28 dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 29 } 30 } 31 printf("%d\n",dp[la][lb]); 32 } 33 return 0; 34 }
原文:http://www.cnblogs.com/haoabcd2010/p/5750719.html