-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathPrintShortestCommonSuperSequence.cpp
66 lines (63 loc) · 1.11 KB
/
PrintShortestCommonSuperSequence.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
#include <bits/stdc++.h>
using namespace std;
int dp[102][102];
int main() {
std::ios::sync_with_stdio(false);
int T, l1, l2;
cin >> T;
string s1, s2;
// cin.ignore(); must be there when using getline(cin, s)
while (T--)
{
memset(dp, 0, sizeof(dp));
cin >> l1 >> l2;
cin >> s1 >> s2;
//BOTTOM-UP APROACH
//int l1 = s1.length(), l2 = s2.length();
for (int i = 1; i <= l1; i++) {
for (int j = 1; j <= l2; j++) {
if (s1[i - 1] == s2[j - 1])
{
dp[i][j] = 1 + dp[i - 1][j - 1];
}
else
{
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
cout << l1 + l2 - dp[l1][l2] << '\n';
int i = l1, j = l2;
list<char> l;
while (i != 0 && j != 0) {
if (s1[i - 1] == s2[j - 1]) {
l.push_front(s2[j - 1]);
i--;
j--;
}
else {
if (dp[i][j - 1] >= dp[i - 1][j]) {
l.push_front(s2[j - 1]);
j--;
}
else {
l.push_front(s1[i - 1]);
i--;
}
}
}
while (i > 0) {
l.push_front(s1[i - 1]);
i--;
}
while (j > 0) {
l.push_front(s2[j - 1]);
j--;
}
for (auto it : l) {
cout << it;
}
cout << '\n';
}
return 0;
}