forked from r0drigopaes/paa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlcs.cpp
135 lines (118 loc) · 2.08 KB
/
lcs.cpp
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
// usado para as versões top_down e bottom_up, mas não é usado para a versão com economia de memória
vector<vi> memo;
string a, b;
int lcs_bottom_memory_trick(int i , int j)
{
vector<vi> small_memo(2);
for (int k=0; k <2; ++k)
{
small_memo[k].resize(j+1, 0);
}
for (int k=0; k <2; ++k)
{
for (int x=0; x <= j; ++x)
{
printf("[%d] ", small_memo[k][x]);
}
printf("\n");
}
int prev = 0, curr = 1;
for (int n=1; n <= i; ++n)
{
for (int m=1; m <= j; ++m)
{
if (a[n-1] == b[m-1])
{
small_memo[curr][m] = 1 + small_memo[prev][m-1];
}
else
{
small_memo[curr][m] = max (small_memo[curr][m-1], small_memo[prev][m]);
}
}
for (int k=0; k <2; ++k)
{
for (int x=0; x <= j; ++x)
{
printf("[%d] ", small_memo[k][x]);
}
printf("\n");
}
printf("\n");
prev = curr;
curr = (curr + 1) %2;
}
return small_memo[1][j];
}
/*
Bottom up sem economia de memória
*/
int lcs_bottomup(int i, int j)
{
for (int k=0; k < i; ++k)
{
memo[k][0] = 0;
}
for (int k=0; k < j; ++k)
{
memo[0][k] = 0;
}
for (int n=1; n <= i; ++n)
{
for (int m=1; m <= j; ++m)
{
if (a[n-1] == b[m-1])
{
memo[n][m] = 1 + memo[n-1][m-1];
}
else
{
memo[n][m] = max (memo[n][m-1], memo[n-1][m]);
}
}
}
return memo[i][j];
}
/*
Top down sem economia de memória
*/
int lcs_topdown(int i, int j)
{
if (memo[i][j] != -1)
{
return memo[i][j];
}
if (i==0 || j==0)
{
memo[i][j] = 0;
}
else
{
if (a[i-1] == b[j-1])
{
memo[i][j] = 1 + lcs_topdown(i-1, j-1);
}
else
{
memo[i][j] = max(lcs_topdown(i, j-1), lcs_topdown(i-1, j));
}
}
return memo[i][j];
}
int main()
{
cin >> a >> b;
// Trecho para as versões sem economia de memória
memo.resize(a.length()+1);
for (int i=0; i <= a.length(); ++i)
{
memo[i].resize(b.length()+1, -1);
}
printf("%d\n", lcs_topdown(a.length(), b.length()) );
// printf("%d\n", lcs_bottomup(a.length(), b.length()) );
// printf("%d\n", lcs_bottom_memory_trick(a.length(), b.length()) );
return 0;
}