-
Notifications
You must be signed in to change notification settings - Fork 0
/
Shortest Common Supersequence
72 lines (64 loc) · 1.44 KB
/
Shortest Common Supersequence
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
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#include <complex>
#include <queue>
#include <set>
#include <unordered_set>
#include <list>
#include <chrono>
#include <random>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <stack>
#include <iomanip>
#include <fstream>
using namespace std;
string SCS(string ans, string &s1, string &s2, int i, int j){
if(i<0 && j<0) return ans;
if(i<0){
while(j>=0){
ans.push_back(s2[j]); j--;
}
reverse(ans.begin(),ans.end());
return ans;
}
if(j<0){
while(i>=0){
ans.push_back(s1[i]); i--;
}
reverse(ans.begin(),ans.end());
return ans;
}
if(s1[i] == s2[j]){
ans = SCS(ans,s1,s2,i-1,j-1);
ans.push_back(s1[i]);
}
else{
string temp1 = SCS(ans,s1,s2,i-1,j);
string temp2 = SCS(ans,s1,s2,i,j-1);
if(temp1.size() < temp2.size()){
ans = temp1; ans.push_back(s1[i]);
}
else{
ans = temp2; ans.push_back(s2[j]);
}
}
return ans;
}
int main(){
string s1, s2;
cin>>s1>>s2;
string ans = "";
int n1 = s1.size();
int n2 = s2.size();
ans = SCS(ans,s1,s2,n1-1,n2-1);
cout<<ans;
return 0;
}