首页 > 其他 > 详细

[UVa Online Judge] Longest Common Subsequence

时间:2015-06-15 00:08:01      阅读:159      评论:0      收藏:0      [点我收藏+]

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 i = 1; i <= m; i++) {
11         if (s[i - 1] == t[0]) cur[i] = 1;
12         else cur[i] = cur[i - 1];
13     }
14     for (int j = 1; j < n; j++) {
15         int pre = 0;
16         for (int i = 1; i <= m; i++) {
17             int temp = cur[i];
18             if (s[i - 1] == t[j]) cur[i] = pre + 1;
19             else cur[i] = max(cur[i], cur[i - 1]);
20             pre = temp;
21         }
22     }
23     return cur[m];
24 }
25 
26 int main(void) {
27     string s, t;
28     while (getline(cin, s)) {
29         getline(cin, t);
30         cout << lcs(s, t) << endl;
31     }
32     return 0;
33 }

Well, try this problem here and get Accepted :)

[UVa Online Judge] Longest Common Subsequence

原文:http://www.cnblogs.com/jcliBlogger/p/4575970.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!