TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
longest_common_subsequence.cpp
1
// Longest common subsequence - Dynamic Programming
2
#include <iostream>
3
#include <vector>
4
using namespace
std;
5
6
void
Print(
int
trace[20][20],
int
m,
int
n,
string
a) {
7
if
(m == 0 || n == 0) {
8
return
;
9
}
10
if
(trace[m][n] == 1) {
11
Print(trace, m - 1, n - 1, a);
12
cout << a[m - 1];
13
}
else
if
(trace[m][n] == 2) {
14
Print(trace, m - 1, n, a);
15
}
else
if
(trace[m][n] == 3) {
16
Print(trace, m, n - 1, a);
17
}
18
}
19
20
int
lcs(
string
a,
string
b) {
21
int
m = a.length(), n = b.length();
22
std::vector<std::vector<int> > res(m + 1, std::vector<int>(n + 1));
23
int
trace[20][20];
24
25
// fills up the arrays with zeros.
26
for
(
int
i = 0; i < m + 1; i++) {
27
for
(
int
j = 0; j < n + 1; j++) {
28
res[i][j] = 0;
29
trace[i][j] = 0;
30
}
31
}
32
33
for
(
int
i = 0; i < m + 1; ++i) {
34
for
(
int
j = 0; j < n + 1; ++j) {
35
if
(i == 0 || j == 0) {
36
res[i][j] = 0;
37
trace[i][j] = 0;
38
}
39
40
else
if
(a[i - 1] == b[j - 1]) {
41
res[i][j] = 1 + res[i - 1][j - 1];
42
trace[i][j] = 1;
// 1 means trace the matrix in upper left
43
// diagonal direction.
44
}
else
{
45
if
(res[i - 1][j] > res[i][j - 1]) {
46
res[i][j] = res[i - 1][j];
47
trace[i][j] =
48
2;
// 2 means trace the matrix in upwards direction.
49
}
else
{
50
res[i][j] = res[i][j - 1];
51
trace[i][j] =
52
3;
// means trace the matrix in left direction.
53
}
54
}
55
}
56
}
57
Print(trace, m, n, a);
58
return
res[m][n];
59
}
60
61
int
main
() {
62
string
a, b;
63
cin >> a >> b;
64
cout << lcs(a, b);
65
return
0;
66
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
dynamic_programming
longest_common_subsequence.cpp
Generated by
1.18.0