最长公共子序列

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <string>
 6 using namespace std;
 7 #define N 1005
 8 int dp[N+1][N+1];
 9 int b[N+1][N+1];
10 char str1[N],str2[N];
11 void lcs(int len1,int len2)
12 {
13     for(int i=0;i<len1;i++){
14         for(int j=0;j<len2;j++){
15             if(str1[i]==str2[j]){
16                 dp[i+1][j+1]=dp[i][j]+1;
17                 b[i+1][j+1]=1;
18             }
19             else if(dp[i][j+1]>dp[i+1][j]){
20                 dp[i+1][j+1]=dp[i][j+1];
21                 b[i+1][j+1]=2;
22             }else{
23                 dp[i+1][j+1]=dp[i+1][j];
24                 b[i+1][j+1]=3;
25             }
26         }
27     }
28     cout<<dp[len1][len2]<<endl;
29 }
30 void printLcs(int i,int j)
31 {
32     if(i==0||j==0) return;
33     else if(b[i][j]==1){
34         printLcs(i-1,j-1);
35         cout<<str1[i-1];
36     }else if(b[i][j]==2) printLcs(i-1,j);
37     else printLcs(i,j-1);
38 }
39 int main()
40 {
41     while(cin>>str1>>str2){
42         memset(dp,0,sizeof(dp));
43         memset(b,0,sizeof(b));
44         int len1=strlen(str1);
45         int len2=strlen(str2);
46         lcs(len1,len2);//求解序列长度
47         printLcs(len1,len2);//打印序列
48     }
49     return 0;
50 }

 

posted @ 2018-12-30 12:13  wydxry  阅读(233)  评论(0编辑  收藏  举报
Live2D