DP:最大公共子序列

POJ1458裸LCS,尽管自己写了,但能看到AC还是很幸福的,感觉LCS的思路比较好理清.

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<string.h>
 4 using namespace std;
 5 char s1[1000];
 6 char s2[1000];
 7 int dp[1005][1005];
 8 int max(int a,int b)
 9 {if(a>=b) return a;else return b;}
10 int main()
11 {
12   //freopen("input.txt","r",stdin);
13   while(scanf("%s%s",s1+1,s2+1)!=EOF){
14   int num1=strlen(s1+1);
15   int num2=strlen(s2+1);
16   //printf("%d %d\n",num1,num2);
17   //printf("%s %s\n",s1+1,s2+1);
18   for(int i=1;i<=num1;i++)
19      for(int j=1;j<=num2;j++)
20         {
21            if(s1[i]==s2[j]) dp[i][j]=dp[i-1][j-1]+1;
22            else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
23         }
24    printf("%d\n",dp[num1][num2]);
25   }
26   return 0;
27 }
View Code


 时间复杂度为O(n*m)  然后自己还得把打印最大公共子序列 敲一下....

或者还有一个时间复杂度更低的??

posted @ 2013-05-25 08:41  闭关修炼的小孩纸  阅读(145)  评论(0编辑  收藏  举报