Skip to content

Commit ef877e3

Browse files
authored
Create Shortest Common Supersequence - DP.cpp
1 parent 3545a87 commit ef877e3

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
// Dynamic programming solution
2+
#include <bits/stdc++.h>
3+
#include <ext/rope>
4+
using namespace std;
5+
using namespace __gnu_cxx;
6+
7+
using ld = long double;
8+
using llint = long long;
9+
using ullint = unsigned long long;
10+
using pii = pair <int,int>;
11+
using pcc = pair <char,char>;
12+
using pss = pair <string,string>;
13+
using vi = vector <int>;
14+
using vb = vector <bool>;
15+
using vii = vi::iterator;
16+
17+
#define INF (1<<30)
18+
#define MOD 1000000007
19+
#define mp make_pair
20+
#define mt make_tuple
21+
#define all(c) c.begin(), c.end()
22+
#define ms(name,val) memset(name, val, sizeof name)
23+
#define np nullptr
24+
25+
26+
int main()
27+
{
28+
ios_base::sync_with_stdio(0);
29+
//cin.tie(0);
30+
31+
string a, b;
32+
cin >> a >> b;
33+
int n = a.size(), m = b.size();
34+
vector <vi> DP(n+1, vi(m+1, 0));
35+
36+
for (int t1 = 0; t1 <= n; ++t1)
37+
{
38+
for (int t2 = 0; t2 <= m; ++t2)
39+
{
40+
if (!t1)
41+
DP[t1][t2] = t2;
42+
else if (!t2)
43+
DP[t1][t2] = t1;
44+
else if (a[t1-1] == b[t2-1])
45+
DP[t1][t2] = 1 + DP[t1-1][t2-1];
46+
else
47+
DP[t1][t2] = 1 + min(DP[t1-1][t2], DP[t1][t2-1]);
48+
}
49+
}
50+
51+
cout << "\nShortest common supersequence:\n";
52+
cout << "Length: " << DP[n][m] << '\n';
53+
cout << "Sequence: ";
54+
string seq;
55+
int x = n, y = m;
56+
57+
while (x && y)
58+
{
59+
if (a[x-1] == b[y-1])
60+
{
61+
seq.push_back(b[y-1]);
62+
--x, --y;
63+
}
64+
else if (DP[x-1][y] < DP[x][y-1])
65+
{
66+
seq.push_back(a[x-1]);
67+
--x;
68+
}
69+
else
70+
{
71+
seq.push_back(b[y-1]);
72+
--y;
73+
}
74+
}
75+
76+
while (x)
77+
{
78+
seq.push_back(a[x-1]);
79+
--x;
80+
}
81+
82+
while (y)
83+
{
84+
seq.push_back(b[y-1]);
85+
--y;
86+
}
87+
88+
reverse(all(seq));
89+
cout << seq << '\n';
90+
91+
92+
93+
return 0;
94+
}

0 commit comments

Comments
 (0)