动态规划——LCS
LCS代码实现
#include<iostream> #include<cstring> #include<algorithm> #define maxn 105 using namespace std; char a[maxn],b[maxn]; int dp[maxn][maxn]; int LCSlength() { memset(dp,0,sizeof(dp)); int alen = strlen(a); int blen = strlen(b); for(int i=0; i<alen; i++) { for(int j=0; j<blen; j++) { if(a[i]==b[j]) { dp[i][j] = dp[i-1][j-1]+1; } else { dp[i][j] = max(dp[i-1][j],dp[i][j-1]); } } } return dp[alen-1][blen-1]; } int main() { while(~scanf("%s %s",a,b)) { int ans = LCSlength(); printf("%d",ans); } return 0; }
递归求LSC序列:
#include<iostream> #include<cstring> #include<algorithm> #define maxn 105 using namespace std; char a[maxn],b[maxn]; int dp[maxn][maxn]; int step[maxn][maxn]; void Print(int i,int j){ if(i<0 || j<0){ return; } if(step[i][j]==1){ Print(i-1,j-1); printf("%c",a[i]); }else if(step[i][j]==2){ Print(i-1,j); }else if(step[i][j]==3){ Print(i,j-1); } } void LCS(){ memset(dp,0,sizeof(dp)); int alen = strlen(a); int blen = strlen(b); for(int i=0;i<alen;i++){ for(int j=0;j<blen;j++){ if(a[i]==b[j]){ dp[i][j] = dp[i-1][j-1]+1; step[i][j] = 1; }else{ if(dp[i-1][j]>dp[i][j-1]){ dp[i][j] = dp[i-1][j]; step[i][j] = 2; }else{ dp[i][j] = dp[i][j-1]; step[i][j] = 3; } } } } cout<<dp[alen-1][blen-1]<<endl; Print(alen-1,blen-1); } int main() { while(~scanf("%s %s",a,b)) { LCS(); } return 0; }
非递归LSC序列: