Skip to content

Commit d8e2493

Browse files
committed
added PrintShortestCommonSupersequence
1 parent 92529a5 commit d8e2493

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
//Print Shortest Common Supersequence
2+
3+
#include<bits/stdc++.h>
4+
using namespace std;
5+
6+
7+
class Solution
8+
{
9+
public:
10+
//Function to find shortest common supersequence string of two strings.
11+
string shortestCommonSupersequence(string x, string y, int m, int n)
12+
{
13+
int dp[m+1][n+1];
14+
15+
for(int i=0; i<=m; i++)
16+
{
17+
for(int j=0; j<=n; j++)
18+
{
19+
if(i == 0 || j == 0)
20+
{
21+
dp[i][j] = 0;
22+
}
23+
else if(x[i-1] == y[j-1])
24+
{
25+
dp[i][j] = dp[i-1][j-1] + 1;
26+
}
27+
else
28+
{
29+
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
30+
}
31+
}
32+
}
33+
34+
int i = m, j = n;
35+
string ans = "";
36+
37+
while(i > 0 && j > 0)
38+
{
39+
if(x[i-1] == y[j-1])
40+
{
41+
ans.push_back(x[i-1]);
42+
i--;
43+
j--;
44+
}
45+
else if(dp[i][j-1] > dp[i-1][j])
46+
{
47+
ans.push_back(y[j-1]);
48+
j--;
49+
}
50+
else
51+
{
52+
ans.push_back(x[i-1]);
53+
i--;
54+
}
55+
}
56+
57+
while(i>0)
58+
{
59+
ans.push_back(x[i-1]);
60+
i--;
61+
}
62+
63+
while(j>0)
64+
{
65+
ans.push_back(y[j-1]);
66+
j--;
67+
}
68+
69+
reverse(ans.begin(), ans.end());
70+
return ans;
71+
}
72+
};
73+
74+
75+
76+
int main()
77+
{
78+
79+
int t;
80+
81+
//taking total testcases
82+
cin >> t;
83+
while(t--){
84+
string X, Y;
85+
//taking String X and Y
86+
cin >> X >> Y;
87+
88+
//calling function shortestCommonSupersequence()
89+
Solution obj;
90+
cout << obj.shortestCommonSupersequence(X, Y, X.size(), Y.size())<< endl;
91+
}
92+
return 0;
93+
}

0 commit comments

Comments
 (0)