-
Notifications
You must be signed in to change notification settings - Fork 1
/
LCS(longest common subsequence)(memorisation).cpp
79 lines (74 loc) · 1.59 KB
/
LCS(longest common subsequence)(memorisation).cpp
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
76
77
78
79
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define fr(i,n) for(int i=0;i<n;i++)
#define fre(i,a,b) for(int i=a;i<=b;i++)
#define endl '\n'
#define no cout << "NO" << endl
#define yes cout << "YES" << endl
#define mem(name, value) memset(name, value, sizeof(name))
#define pb push_back
#define ff first
#define ss second
#define mp make_pair
#define all(v) (v).begin(), (v).end()
#define case cout << "Case " << t++ << ": ";
// Recursive Soln for LCS
int LCS_Rec(string str1,string str2, int a,int b){
if(a == 0 || b == 0)
{
return 0;
}
if(str1[a-1] == str2[b-1])
{
return (1 + LCS(str1,str2,a-1,b-1));
}
else
return max(LCS(str1,str2,a,b-1), LCS(str1,str2,a-1,b));
}
// Top down DP optimisation
int LCS(string str1, string str2, int a, int b) {
int dp[10001][10001];
for (int i = 0; i <= a; i++) {
dp[i][0] = {0};
}
for (int j = 0; j <= b; j++) {
dp[0][j] = {0};
}
for (i = 1; i <= a; i++)
{
for (j = 1; j <= b; j++) {
int ans = 0;
if (str1[i - 1] == str2[j - 1]) {
ans = 1 + dp[i - 1][j - 1];
}
else {
ans = max(dp[i - 1][j], dp[i][j - 1])
}
dp[i][j] = ans;
}
}
return dp[a][b];
}
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin) ;
freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--)
{
string str1;
string str2;
cin >> str1 >> str2;
int m = str1.length();
int n = str2.length();
cout << LCS(str1, str2, m, n) << endl;
}
return 0;
}