[UVa OJ] Longest Common Subsequence

简介: This is the classic LCS problem. Since it only requires you to print the maximum length, the code can be optimized to use only O(m) space (see here).

This is the classic LCS problem. Since it only requires you to print the maximum length, the code can be optimized to use only O(m) space (see here).

My accepted code is as follows.

 

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 
 5 using namespace std;
 6 
 7 int lcs(string s, string t) {
 8     int m = s.length(), n = t.length();
 9     vector<int> cur(m + 1, 0);
10     for (int j = 1; j <= n; j++) {
11         int pre = 0;
12         for (int i = 1; i <= m; i++) {
13             int temp = cur[i];
14             cur[i] = (s[i - 1] == t[j - 1] ? pre + 1 : max(cur[i], cur[i - 1]));
15             pre = temp;
16         }
17     }
18     return cur[m];
19 }
20 
21 int main(void) {
22     string s, t;
23     while (getline(cin, s)) {
24         getline(cin, t);
25         printf("%d\n", lcs(s, t));
26     }
27     return 0;
28 }

 

Well, try this problem here and get Accepted :)

目录
相关文章
|
8月前
|
人工智能
HDU-1159-Common Subsequence
HDU-1159-Common Subsequence
47 0
|
8月前
poj-1458-Common Subsequence
poj-1458-Common Subsequence
39 0
|
人工智能 BI
UVA live 2678 - Subsequence
关于这个题目,有多种的解法,如果枚举起点和终点,时间复杂度为O(n^3),但如果我们用一个数组B把一段数的和存起来,B[i] = sum(a[1].....a[i])。这样就可以把时间复杂度降到O(n^2)。
88 0
POJ-1458,Common Subsequence(经典DP)
POJ-1458,Common Subsequence(经典DP)
|
人工智能
POJ 2533 Longest Ordered Subsequence
POJ 2533 Longest Ordered Subsequence
117 0
|
机器学习/深度学习 网络架构
题解 UVA10212 【The Last Non-zero Digit.】
题目链接 这题在学长讲完之后和看完题解之后才明白函数怎么构造。这题构造一个$f(n)$$f(n)$ $=$ $n$除以 $2^{a}$ $*$ $5^{b}$ ,$a$ , $b$ 分别是 $n$ 质因数分解后$2,5$的个数。
1239 0

热门文章

最新文章