-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11_LCS.cpp
More file actions
76 lines (68 loc) · 1.29 KB
/
11_LCS.cpp
File metadata and controls
76 lines (68 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* P434 最长公共子序列
* 动态规划
* 还是就考虑右端点
*/
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
// 字符串
string strA;
string strB;
// dp 数组
int **dp;
// init
void init()
{
cout << "Input the 2 string: " << endl;
getline(cin, strA);
getline(cin, strB);
// initialize dp
// dp[i][j],i 是 strA 长度,j 是 strB 长度
dp = new int*[strA.length() + 1];
for (int i = 0; i <= strA.length(); i++)
{
dp[i] = new int[strB.length() + 1];
}
// 边界
for (int i = 0; i <= strA.length(); i++)
{
dp[i][0] = 0;
}
for (int j = 0; j <= strB.length(); j++)
{
dp[0][j] = 0;
}
}
// main function
void calLCS()
{
for (int i = 1; i <= strA.length(); i++)
{
for (int j = 1; j <= strB.length(); j++)
{
// 状态转移方程
if (strA[i] == strB[j])
{
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else
{
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
}
void print()
{
cout << "LCS is: " << dp[strA.length()][strB.length()] << endl;
}
int main()
{
init();
calLCS();
print();
return 0;
}