码迷,mamicode.com
首页 > 其他好文 > 详细

[UVa Online Judge] Longest Common Subsequence

时间:2015-06-15 00:10:20      阅读:157      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!