1+ #include " ../headers.hpp"
2+ /*
3+ Sample Test Case :
4+ 2
5+ Enter Two Strings : hegstu hgxsttu
6+ Enter Two Strings : abedfhr abcdgh
7+ OUTPUT using Bottom Up Approach :
8+ case #1 : 5
9+ case #2 : 4
10+ OUTPUT using Top Down Approach :
11+ case #1 : 5
12+ case #2 : 4
13+ */
14+ int LCS_memoized (string str1, string str2, int n, int m, int **dp)
15+ {
16+ if (n == 0 || m == 0 )
17+ return 0 ;
18+
19+ if (dp[n][m] != -1 )
20+ return dp[n][m];
21+
22+ if (str1[n - 1 ] == str2[m - 1 ])
23+ return dp[n][m] = (1 + LCS_memoized (str1, str2, n - 1 , m - 1 , dp));
24+ else
25+ return dp[n][m] = max (LCS_memoized (str1, str2, n - 1 , m, dp), LCS_memoized (str1, str2, n, m - 1 , dp));
26+ }
27+
28+ int LCS_topDown (string s1, string s2, int n, int m)
29+ {
30+ int dp[n + 1 ][m + 1 ];
31+ // Init the dp for base case -> n==0 || m==0 must return 0;
32+ for (int i = 0 ; i <= m; i++)
33+ dp[0 ][i] = 0 ;
34+ for (int i = 0 ; i <= n; i++)
35+ dp[i][0 ] = 0 ;
36+
37+ for (int i = 1 ; i <= n; i++)
38+ {
39+ for (int j = 1 ; j <= m; j++)
40+ {
41+ if (s1[i - 1 ] == s2[j - 1 ])
42+ dp[i][j] = (1 + dp[i - 1 ][j - 1 ]);
43+ else
44+ {
45+ dp[i][j] = max (dp[i - 1 ][j], dp[i][j - 1 ]);
46+ }
47+ }
48+ }
49+ return dp[n][m];
50+ }
51+ int main ()
52+ {
53+ vi output1, output2;
54+ // Output1 stores solns for the Bottom Up approach.
55+ // Output2 stores solns for the Top Down approach.
56+ tests (t)
57+ {
58+ string str1, str2;
59+ cout << " Enter Two Strings : " ;
60+ cin >> str1 >> str2;
61+ int n = str1.size (), m = str2.size ();
62+
63+ int **dp = new int *[n + 1 ];
64+ loop (i, n + 1 ) dp[i] = new int [m + 1 ];
65+
66+ loop (i, n + 1 )
67+ loop (j, m + 1 )
68+ dp[i][j] = -1 ;
69+
70+ output1.pb (LCS_memoized (str1, str2, n, m, dp));
71+ output2.pb (LCS_topDown (str1, str2, n, m));
72+ }
73+ cout << " OUTPUT using Bottom Up Approach : \n " ;
74+ loop (i, output1.size ()) cout << " case #" << i + 1 << " : " << output1[i] << endl;
75+ cout << " OUTPUT using Top Down Approach : \n " ;
76+ loop (i, output2.size ()) cout << " case #" << i + 1 << " : " << output2[i] << endl;
77+ return 0 ;
78+ }
0 commit comments