[HackerRank] The Longest Common Subsequence

This is the classic LCS problem. Since it requires you to print one longest common subsequence, just use the O(m*n)-space version here.

My accepted code is as follows.

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 vector<int> lcs(vector<int>& a, vector<int>& b) {
 8     int n = a.size(), m = b.size();
 9     vector<vector<int> > dp(n + 1, vector<int> (m + 1, 0));
10     for (int i = 1 ;i <= n; i++) {
11         for (int j = 1; j <= m; j++) {
12             if (a[i - 1] == b[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
13             else dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
14         }
15     }
16     vector<int> res;
17     for (int i = n, j = m; i >= 1 && j >= 1;) {
18         if (a[i - 1] == b[j - 1]) {
19             res.push_back(a[i - 1]);
20             i--;
21             j--;
22         }
23         else if (dp[i - 1][j] >= dp[i][j - 1]) i--;
24         else j--;
25     }
26     reverse(res.begin(), res.end());
27     return res;
28 }
29 
30 int main() {
31     /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
32     int n, m;
33     while (scanf("%d %d", &n, &m) != EOF) {
34         vector<int> a(n);
35         vector<int> b(m);
36         for (int i = 0; i < n; i++)
37             scanf("%d", &a[i]);
38         for (int i = 0; i < m; i++)
39             scanf("%d", &b[i]);
40         vector<int> res = lcs(a, b);
41         for (int i = 0; i < (int)res.size(); i++)
42             printf("%d ", res[i]);
43         printf("\n");
44     }
45     return 0;
46 }

 Well, try this problem here and get Accepted :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值