题目地址:
http://acm.hdu.edu.cn/showproblem.php?pid=1159
题目概述:
给出两个字符串,求最长公共子序列长度。
大致思路:
很经典的问题,就不多说了。
附一个我觉得写的很不错的博主的讲解:http://www.cnblogs.com/en-heng/p/3963803.html
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cmath> 5 #include <vector> 6 #include <ctime> 7 #include <map> 8 #include <stack> 9 #include <queue> 10 #include <cstring> 11 #include <algorithm> 12 using namespace std; 13 14 #define sacnf scanf 15 #define scnaf scanf 16 #define scanfi(x) scanf("%d",&x) 17 #define scanfd(x) scanf("%lf",&x) 18 #define scanfl(x) scanf("%lld",&x) 19 #define scanfc(x) scanf("%c",&x) 20 #define scanfs(x) scanf("%s",x) 21 #define maxn 1010 22 #define maxm 10010 23 #define inf 1061109567 24 #define Eps 0.00001 25 const double PI=acos(-1.0); 26 #define mod 1000000007 27 #define MAXNUM 10000 28 void Swap(int &a,int &b) {int t=a;a=b;b=t;} 29 int Abs(int x) {return (x<0)?-x:x;} 30 typedef long long ll; 31 typedef unsigned int uint; 32 33 int dp[maxn][maxn]; 34 char s1[maxn],s2[maxn]; 35 36 int main() 37 { 38 //freopen("data.in","r",stdin); 39 //freopen("data.out","w",stdout); 40 //clock_t st=clock(); 41 while(~scanf("%s%s",s1+1,s2+1)) 42 { 43 s1[0]='s';s2[0]='s'; 44 int len1=strlen(s1); 45 int len2=strlen(s2); 46 memset(dp,0,sizeof(dp)); 47 //if(len1>len2) swap(s1,s2),swap(len1,len2); 48 for(int i=1;i<len1;i++) 49 { 50 for(int j=1;j<len2;j++) 51 { 52 if(s1[i]==s2[j]) dp[i][j]=dp[i-1][j-1]+1; 53 else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 54 } 55 } 56 printf("%d ",dp[len1-1][len2-1]); 57 } 58 //clock_t ed=clock(); 59 //printf(" Time Used : %.5lf Ms. ",(double)(ed-st)/CLOCKS_PER_SEC); 60 return 0; 61 }