-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlcs_scs.cpp
71 lines (58 loc) · 1.72 KB
/
lcs_scs.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
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
/// @brief Retorna a maior subsequencia entre as strings s1 e s2
/// @param s1
/// @param s2
/// @return maior subsequencia entre s1 e s2
string lcs(string &s1, string &s2) {
vector t(s1.size() + 1, vector<int>(s2.size() + 1, 0));
for(int i = s1.size() - 1; i >= 0; i--) {
for(int j = s2.size() - 1; j >= 0; j--) {
if(s1[i] == s2[j]) t[i][j] = t[i + 1][j + 1] + 1;
else t[i][j] = max(t[i + 1][j], t[i][j + 1]);
}
}
string s;
int i = 0, j = 0;
while(i < s1.size() && j < s2.size()) {
if(s1[i] == s2[j]) {
s.push_back(s1[i]);
i++; j++;
} else if(t[i + 1][j] >= t[i][j + 1]) i++;
else j++;
}
return s;
}
/// @brief Retorna a menor supersequencia entre as strings s1 e s2
/// @param s1
/// @param s2
/// @return menor supersequencia entre s1 e s2
string scs(string &s1, string &s2) {
int m = s1.size(), n = s2.size();
vector t(m + 1, vector<int>(n + 1, 0));
for(int i{0}; i <= m; i++) {
for(int j{0}; j <= n; j++) {
if(!i) t[0][j] = j;
else if(!j) t[i][0] = i;
else if(s1[i - 1] == s2[j - 1]) t[i][j] = 1 + t[i - 1][j - 1];
else t[i][j] = 1 + min(t[i - 1][j], t[i][j - 1]);
}
}
string s = "";
int len = t[m][n], i = m, j = n;
while(len--) {
if(i && j && s1[i - 1] == s2[j - 1]) {
s += s1[i - 1];
i--; j--;
} else if(j && t[i][j] - 1 == t[i][j - 1]) {
s += s2[j - 1];
j--;
} else if(i) {
s += s1[i - 1];
i--;
}
}
reverse(s.begin(), s.end());
return s;
}