ZOJ1733 | | HDU1159简单的DP求两个字符串最大子序列的长度,没啥好说的,照着书上敲得。
View Code
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4 #define MAX 1000
5
6 int c[MAX][MAX],len1,len2;
7 char x[MAX],y[MAX];
8 void LCSLength(int m,int n,char *x,char *y)
9 {
10 int i,j;
11 for(i=0; i<m; i++)
12 c[i][0] = 0;
13 for(i=0; i<n; i++)
14 c[0][i] = 0;
15 for(i=0; i<m; i++)
16 for(j=0; j<n; j++)
17 {
18 if(x[i] == y[j])
19 {
20 c[i+1][j+1] = c[i][j] + 1;
21 }
22 else if(c[i][j+1] >= c[i+1][j])
23 {
24 c[i+1][j+1] = c[i][j+1];
25 }
26 else
27 {
28 c[i+1][j+1] = c[i+1][j];
29 }
30 }
31 }
32
33 int main()
34 {
35
36 while(scanf("%s%s",x,y) != EOF )
37 {
38 getchar();
39 len1 = strlen(x);
40 len2 = strlen(y);
41 LCSLength(len1,len2,x,y);
42 printf("%d\n",c[len1][len2]);
43 }
44 return 0;
45 }