-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCS_Reconstruction.cpp
More file actions
75 lines (58 loc) · 1.19 KB
/
LCS_Reconstruction.cpp
File metadata and controls
75 lines (58 loc) · 1.19 KB
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
73
74
75
#include <bits/stdc++.h>
using namespace std;
int n, m;
string a, b;
int dp[3005][3005];
int rec(int i, int j){
// return the LCS of a[i...n-1] and b[j...m-1]
// base case
if(i >= n || j >= m){
return 0;
}
// memoization
if(dp[i][j] != -1){
return dp[i][j];
}
// compute
int ans = 0;
ans = max(ans, rec(i + 1, j));
ans = max(ans, rec(i, j + 1));
if(a[i] == b[j]){
ans = max(ans, 1 + rec(i + 1, j + 1));
}
// save and return
return dp[i][j] = ans;
}
void generate(int i, int j){
if(i >= n || j >= m){
return;
}
if(a[i] == b[j]){
cout << a[i];
generate(i + 1, j + 1);
}
else{
// use dp instead of rec to avoid extra recursion
if(dp[i+1][j] >= dp[i][j+1]){
generate(i + 1, j);
}
else{
generate(i, j + 1);
}
}
}
void solve(){
cin >> a >> b;
n = a.length();
m = b.length();
memset(dp, -1, sizeof(dp));
rec(0, 0); // fill dp
generate(0, 0); // reconstruct answer
cout << endl;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
}