实验9LCS算法

问题:

给定序列$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 <= len1; ++i)    dp[i][0] = 0;
 2 for (int i = 0; i <= len2; ++i)    dp[0][i] = 0;
 3 for (int i = 1; i <= len1; ++i) {
 4     for (int j = 1; j <= len2; ++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<bits/stdc++.h>
 2 #include <set>
 3 #include <map>
 4 #include <stack>
 5 #include <cmath>
 6 #include <queue>
 7 #include <cstdio>
 8 #include <string>
 9 #include <vector>
10 #include <cstring>
11 #include <iostream>
12 #include <algorithm>
13 
14 #define ll long long
15 #define pll pair<ll,ll>
16 #define pii pair<int,int>
17 #define bug printf("*********
")
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 root<<1
22 #define rs root<<1|1
23 #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 <= len1; ++i)    dp[i][0] = 0;
40     for (int i = 0; i <= len2; ++i)    dp[0][i] = 0;
41     for (int i = 1; i <= len1; ++i) {
42         for (int j = 1; j <= len2; ++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长度:" << dp[len1][len2] << endl;
73     cout << "LCS:" << ans << endl;
74 }
View Code
原文地址:https://www.cnblogs.com/zhang-Kelly/p/12797623.html