HackerRank# The Longest Common Subsequence

原题地址

 

LCD,经典动归,O(n^2)复杂度

因为要输出子序列,所以啰嗦一些

 

 1 #include <cmath>
 2 #include <cstdio>
 3 #include <vector>
 4 #include <iostream>
 5 #include <algorithm>
 6 #include <cstring>
 7 using namespace std;
 8 
 9 #define MAX_LEN 128
10 
11 int n, m;
12 int a[MAX_LEN], b[MAX_LEN];
13 int lcd[MAX_LEN][MAX_LEN];
14 int start_index_a[MAX_LEN][MAX_LEN];
15 int start_index_b[MAX_LEN][MAX_LEN];
16 
17 int main() {
18     /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
19     cin >> n >> m;
20     for (int i = 0; i < n; i++)
21         cin >> a[i];
22     for (int i = 0; i < m; i++)
23         cin >> b[i];
24     memset(lcd, 0, sizeof(lcd));
25     memset(start_index_a, 0, sizeof(start_index_a));
26     for (int j = 0; j < m; j++)
27         start_index_a[n][j] = start_index_b[n][j] = -1;
28     for (int i = 0; i < n; i++)
29         start_index_a[i][m] = start_index_b[i][m] = -1;
30     for (int i = n - 1; i >= 0; i--) {
31         for (int j = m - 1; j >= 0; j--) {
32             if (a[i] == b[j]) {
33                 lcd[i][j] = lcd[i + 1][j + 1] + 1;
34                 start_index_a[i][j] = i;
35                 start_index_b[i][j] = j;
36             } else if (lcd[i + 1][j] > lcd[i][j + 1]) {
37                 lcd[i][j] = lcd[i + 1][j];
38                 start_index_a[i][j] = start_index_a[i + 1][j];
39                 start_index_b[i][j] = start_index_b[i + 1][j];
40             } else {
41                 lcd[i][j] = lcd[i][j + 1];
42                 start_index_a[i][j] = start_index_a[i][j + 1];
43                 start_index_b[i][j] = start_index_b[i][j + 1];
44             }
45         }
46     }
47     
48     int i = start_index_a[0][0];
49     int j = start_index_b[0][0];
50     while (i >= 0 && j >= 0) {
51         cout << a[i] << " ";
52         int ii = start_index_a[i + 1][j + 1];
53         int jj = start_index_b[i + 1][j + 1];
54         i = ii;
55         j = jj;
56     }
57     cout << endl;
58     return 0;
59 }

 

转载于:https://www.cnblogs.com/boring09/p/4483655.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值