-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlcs_print.cpp
More file actions
66 lines (52 loc) · 1.38 KB
/
lcs_print.cpp
File metadata and controls
66 lines (52 loc) · 1.38 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
//LONGEST COMMON SUBSEQUENCE BOTTOM-UP aproach printing the subsequence
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAXN = 101;
int main()
{
int n, m;
int dp[MAXN][MAXN];
int A[MAXN], B[MAXN];
cin >> n >> m;
for (int i = 0; i < n; i++)
cin >> A[i];
for (int i = 0; i < m; i++)
cin >> B[i];
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
if (A[i - 1] != B[j - 1])
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
else
dp[i][j] = dp[i - 1][j - 1] + 1;
}
}
cout << "Size of the Longest Commom Subsequence: " << dp[n][m] << endl;
// Recuperando a resposta
vector<int> MSC; // A MSC será guardado nesse vector
int i = n, j = m;
while (i != 0 && j != 0)
{
if (A[i - 1] == B[j - 1]) // A[i - 1] e B[j - 1] estão na MSC
{
MSC.push_back(A[i - 1]);
i--;
j--;
}
else
{
if (dp[i - 1][j] > dp[i][j - 1]) // Decidindo qual é o melhor estado para ir
i--;
else
j--;
}
}
// Revertendo a resposta
reverse(MSC.begin(), MSC.end());
cout << "Maior subsequência comum: ";
for (int i = 0; i < (int)MSC.size(); i++)
cout << MSC[i] << " ";
}