实验9LCS算法

2021-02-04 04:16

阅读:807

标签:output   iostream   string   closed   cli   stdout   play   display   bsp   

问题:

给定序列$X,Y$,求最长公共子序列。

解析:

设$dp[i][j]$表示前$i$个$x$和前$j$个$y$的最长公共子序列。

$dp[i][j]=max(dp[i][j],dp[i-1][j],dp[i][j-1])$  当前最长由前一个转移过来

$if(x[i]==y[j]) dp[i][j]=max(dp[i][j],dp[i-1][j-1]+1)$   如果当前两位相等,最长序列长度$+1$

设计(核心代码):

 1 for (int i = 0; i 0] = 0;
 2 for (int i = 0; i 0][i] = 0;
 3 for (int i = 1; i i) {
 4     for (int j = 1; j j) {
 5         if (x[i] == y[j]) {
 6             dp[i][j] = dp[i - 1][j - 1] + 1;
 7         }
 8         else {
 9             if (dp[i - 1][j] > dp[i][j - 1]) {
10                 del[i][j] = 1;
11                 dp[i][j] = dp[i - 1][j];
12             }
13             else {
14                 del[i][j] = 2;
15                 dp[i][j] = dp[i][j - 1];
16             }
17         }
18     }
19 }

分析:

$O(n*m)$。

源码:

https://github.com/Big-Kelly/Algorithm

技术图片技术图片
 1 //#include
 2 #include set>
 3 #include  4 #include  5 #include  6 #include  7 #include  8 #include string>
 9 #include 10 #include 11 #include 12 #include 
13 
14 #define ll long long
15 #define pll pair16 #define pii pair17 #define bug printf("*********\n")
18 #define FIN freopen("input.txt","r",stdin);
19 #define FON freopen("output.txt","w+",stdout);
20 #define IO ios::sync_with_stdio(false),cin.tie(0)
21 #define ls root22 #define rs root23 #define pb push_back
24 
25 using namespace std;
26 const int inf = 2e9 + 7;
27 const ll Inf = 1e18 + 7;
28 const int maxn = 5e3 + 5;
29 const ll mod = 998244353;
30 
31 string x, y, ans;
32 int len1, len2;
33 int dp[maxn][maxn], del[maxn][maxn];
34 
35 int main() {
36     cin >> x >> y;
37     len1 = x.length(), len2 = y.length();
38     x = " " + x, y = " " + y;
39     for (int i = 0; i 0] = 0;
40     for (int i = 0; i 0][i] = 0;
41     for (int i = 1; i i) {
42         for (int j = 1; j j) {
43             if (x[i] == y[j]) {
44                 dp[i][j] = dp[i - 1][j - 1] + 1;
45             }
46             else {
47                 if (dp[i - 1][j] > dp[i][j - 1]) {
48                     del[i][j] = 1;
49                     dp[i][j] = dp[i - 1][j];
50                 }
51                 else {
52                     del[i][j] = 2;
53                     dp[i][j] = dp[i][j - 1];
54                 }
55             }
56         }
57     }
58     int i = len1, j = len2;
59     ans = "";
60     while (i && j) {
61         if (!del[i][j]) {
62             ans = x[i] + ans;
63             i--, j--;
64         }
65         else if (del[i][j] == 1) {
66             i--;
67         }
68         else {
69             j--;
70         }
71     }
72     cout "LCS长度:"  endl;
73     cout "LCS:"  endl;
74 }
View Code

 

实验9LCS算法

标签:output   iostream   string   closed   cli   stdout   play   display   bsp   

原文地址:https://www.cnblogs.com/zhang-Kelly/p/12797623.html

上一篇:python基础语法5

下一篇:C语言for循环


评论


亲,登录后才可以留言!