-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCS_2str.cpp
More file actions
51 lines (37 loc) · 758 Bytes
/
LCS_2str.cpp
File metadata and controls
51 lines (37 loc) · 758 Bytes
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
#include <bits/stdc++.h>
using namespace std;
int n, m;
string a, b;
int dp[1001][1001];
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 solve(){
cin >> n >> m;
cin >> a >> b;
memset(dp, -1, sizeof(dp));
cout << rec(0, 0) << endl;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
}