dp--最长公共子序列LCS

 

 

给定两个字符串,求解这两个字符串的最长公共子序列(Longest Common Sequence)。比如字符串1:BDCABA;字符串2:ABCBDAB

则这两个字符串的最长公共子序列长度为4,最长公共子序列是:BCBA

 

核心思想

 

这张图片可以很好的理解lcs

 例题    hdu1423

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <cmath>
 6 using namespace std;
 7 
 8 #define mem(a) memset(a,0,sizeof(a))
 9 #define ll long long
10 const int maxn = 600;
11 ll a[maxn],b[maxn];
12 int dp[maxn][maxn];
13 
14 int main()
15 {
16     ios::sync_with_stdio(false);
17     cin.tie(0),cout.tie(0);
18     int t,n,m;
19     cin>>t;
20     while(t--)
21     {
22         cin>>n;
23         for(int i = 1; i <= n; i++)
24         {
25             cin>>a[i];
26         }
27         cin>>m;
28         for(int j = 1; j <= m; j++)
29         {
30             cin>>b[j];
31         }
32         mem(dp);
33         int temp = INT_MIN;
34         for(int i = 1; i <= n; i++)
35         {
36             for(int j = 1; j <= m; j++)
37             {
38                 if(a[i] == b[j] && a[i] >= temp)//上升
39                 {
40                     dp[i][j] = dp[i-1][j-1] + 1;
41                     temp = a[i];
42                 }
43                 else
44                     dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
45             }
46         }
47         cout<<dp[n][m]<<endl;
48         if(t)
49             cout<<endl;
50     }
51     return 0;
52 }
LCS

 

posted on 2019-08-17 16:37  By_布衣  阅读(103)  评论(0编辑  收藏  举报

导航