最长公共子序列(lcs)

给出两个字符串A B,求A与B的最长公共子序列(子序列不要求是连续的)。
 
比如两个串为:

abcicba
abdkscab

ab是两个串的子序列,abc也是,abca也是,其中abca是这两个字符串最长的子序列。

Input

第1行:字符串A
第2行:字符串B
(A,B的长度 <= 1000)Output输出最长的子序列,如果有多个,随意输出1个。Sample Input

abcicba
abdkscab

Sample Output

abca
题解:求最长公共子序列,并打印,先求出最长公共子序列,然后回溯即可。
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 #include<stack>
 5 #include<queue>
 6 #include<iostream>
 7 #include<map>
 8 #include<vector>
 9 #define Inf 0x3f3f3f3f
10 #define PI acos(-1.0)
11 using namespace std;
12 int str[1234];
13 int ans[1244];
14 int dp[1234][1234];
15 int len=1;
16 int main()
17 {
18     char str1[1234],str2[1234];
19     int len1,len2;
20     scanf("%s %s",&str1,&str2);
21         stack<char>ss;
22         while(!ss.empty())
23         {
24             ss.pop();
25         }
26         len1=strlen(str1);
27         for(int i=len1; i>=1; i--)
28         {
29             str1[i]=str1[i-1];
30         }
31         len2=strlen(str2);
32         for(int i=len2; i>=1; i--)
33         {
34             str2[i]=str2[i-1];
35         }
36         memset(dp,0,sizeof(dp));
37         for(int i=1; i<=len1; i++)
38             for(int j=1; j<=len2; j++)
39             {
40                 if(str1[i]==str2[j])
41                 {
42                     dp[i][j]=dp[i-1][j-1]+1;
43                 }
44                 else
45                 {
46 
47                     dp[i][j]=max(dp[i][j-1],dp[i-1][j]);
48                 }
49             }
50         int m=dp[len1][len2];
51         int j=len2;
52         for(int i=len1; i>=1; i--){
53                 if(j<1)
54                 break;
55             if(str1[i]==str2[j])
56             {
57                 j--;
58                 ss.push(str1[i]);
59 
60             }
61             else
62             {
63                 if(dp[i][j-1]>dp[i-1][j])
64                 {
65                     i++;
66                     j=j-1;
67 
68                 }
69             }
70     }
71     while(!ss.empty())
72     {
73         printf("%c",ss.top());
74         ss.pop();
75         }
76         puts("");
77 
78 return 0;
79 }
View Code

 

posted @ 2018-07-29 13:52  sdibt布谷鸟  阅读(258)  评论(0编辑  收藏  举报