http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1346
明天写题解!!!!
问题描述:求最长公共子序列
1、递推求解:
#include<iostream> #include<algorithm> #include<string.h> #include<stdio.h> using namespace std; char s1[1100],s2[1100]; int c[1100][1100]; int LCS(){ int n=strlen(s1); int m=strlen(s2); memset(c,0,sizeof(c)); for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if (s1[i-1]==s2[j-1]) c[i][j]+=c[i-1][j-1]+1; else c[i][j]=max(c[i-1][j],c[i][j-1]); } } return c[n][m]; } int main(){ // freopen("in","rb",stdin); // freopen("out","wb",stdout); while(~scanf("%s%s",s1,s2)){ printf("%d ",LCS()); } return 0; }
算法证明:
2、递归解法:
#include<iostream> #include<string.h> #include<stdio.h> using namespace std; int vis[1005][1005]; int c[1005][1005]; char s1[1005],s2[1005]; int LCS(int l,int r){ int &ans=c[l][r]; if (l==0 || r==0) return ans=0; if(vis[l][r]) return ans; vis[l][r]=1; if (s1[l-1]==s2[r-1]) ans=LCS(l-1,r-1)+1; else ans=max(LCS(l-1,r),LCS(l,r-1)); return ans; } int main(){ // freopen("in","rb",stdin); // freopen("out","wb",stdout); while(~scanf("%s%s",s1,s2)){ int l=strlen(s1),r=strlen(s2); memset(vis,0,sizeof(vis)); printf("%d ",LCS(l,r)); } }