hdu 1159 Common Subsequence

经典DP题目:

状态转移方程:if(a[j] == b[i]) table[i][j] = table[i-1][j-1] + 1;
else table[i][j] = max(table[i-1][j],table[i][j-1]);

把a串看成横行,b串看成数列,依次相同加1,看斜角

  题目传送门

 1 #include<stdio.h>
 2 #include<string.h>
 3 char a[1003],b[1003];
 4 int table[1003][1003];
 5 int max(int a, int b)
 6 {
 7     return a>b?a:b;
 8 }
 9 int main()
10 {
11     int len1,len2,flag,i,j;
12     while(scanf("%s %s",a,b)!=EOF)
13     {
14         len1 = strlen(a);
15         len2 = strlen(b);
16         flag = 0;
17         for(i=0;i<len1;i++)
18         {
19             if(b[0] == a[i]) flag = 1;
20             if(flag) table[0][i] = 1;
21             else table[0][i] = 0;
22         }
23         flag = 0;
24         for(i=0;i<len2;i++)
25         {
26             if(a[0] == b[i]) flag = 1;
27             if(flag) table[i][0] = 1;
28             else table[i][0] = 0;
29         }
30         for(i=1;i<len2;i++)
31             for(j=1;j<len1;j++)
32                 if(a[j] == b[i]) table[i][j] = table[i-1][j-1] + 1;
33                 else table[i][j] = max(table[i-1][j],table[i][j-1]);
34         printf("%d\n",table[len2-1][len1-1]);
35     }
36     return 0;
37 }

 

posted @ 2013-05-11 21:04  飞向梦  阅读(145)  评论(0编辑  收藏  举报