题目:http://acm.hdu.edu.cn/showproblem.php?pid=1159
问题的递归式写成:
代码:
#include<stdio.h> #include<string.h> #define MAXLEN 505 void LCSLength(char *x,char *y,int m,int n,int c[][MAXLEN]){//求最长公共子序列; int i,j; for(i=0;i<=m;i++){ c[i][0]=0; } for(i=0;i<=n;i++){ c[0][i]=0; } for(i=1;i<=m;i++){ for(j=1;j<=n;j++){ if(x[i-1]==y[j-1]){ c[i][j]=c[i-1][j-1]+1; } else if(c[i-1][j]>c[i][j-1]){ c[i][j]=c[i-1][j]; } else{ c[i][j]=c[i][j-1]; } } } } int main(){ char s[MAXLEN],s1[MAXLEN],s2[MAXLEN]; int len,i,j,len1,len2,cnt,c[MAXLEN][MAXLEN]; while(scanf(" %s %s",s1,s2)!=EOF){ /*len=strlen(s); i=0; len1=1;//下表从1开始; len2=1; while(s[i]!=' '){ s1[len1++]=s[i++]; } len1--; while(s[i]==' '){ i++;//跳过中间的空格; } while(i<len&&s2[i]!=' '){ s2[len2++]=s[i++]; } len2--;*/ len1=strlen(s1); len2=strlen(s2); LCSLength(s1,s2,len1,len2,c); printf("%d/n",c[len1][len2]); } }