From a2823b502fa663c599b10618209dec2caa1728ed Mon Sep 17 00:00:00 2001 From: Prabir Tarafdar Date: Mon, 9 Aug 2021 18:25:57 +0530 Subject: [PATCH] chore(CPlusPlus): add Matrix Chain Multiplication to Dynamic Programming (#410) Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com> --- .../matrix-chain-multiplication.cpp | 56 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 3 +- 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 algorithms/CPlusPlus/Dynamic-Programming/matrix-chain-multiplication.cpp diff --git a/algorithms/CPlusPlus/Dynamic-Programming/matrix-chain-multiplication.cpp b/algorithms/CPlusPlus/Dynamic-Programming/matrix-chain-multiplication.cpp new file mode 100644 index 00000000..0da91658 --- /dev/null +++ b/algorithms/CPlusPlus/Dynamic-Programming/matrix-chain-multiplication.cpp @@ -0,0 +1,56 @@ +// Matrix Chain Multiplicatin - Memorization-Approuch + +#include +using namespace std; + +// Function for matrix chain multiplication +int matrixChainMulti(vector &arr, const int i, const int j, vector> &dp) +{ + if (i >= j) + return 0; + + if (dp[i][j] != -1) + return dp[i][j]; + + int countMin = INT_MAX; + for (int k = i; k < j; k++) + { + int temp_ans = matrixChainMulti(arr, i, k, dp) + matrixChainMulti(arr, k + 1, j, dp) + (arr[i - 1] * arr[k] * arr[j]); + if (temp_ans < countMin) + countMin = temp_ans; + } + return dp[i][j] = countMin; +} + +// Driver Code +int main() +{ + // dp table initialized with -1 + vector> dp(1001, vector(1001, -1)); + + int n; + cout << "Enter the array size." << endl; + cin >> n; + vector arr(n); + cout << "Enter all the array elements." << endl; + for (int i = 0; i < n; i++) + cin >> arr[i]; + + cout << "Minimum number of multiplications is" << endl; + cout << matrixChainMulti(arr, 1, n - 1, dp) << endl; +} + +/* + * Time Complexity: O(N^3) + * Auxiliary Space: O(N^2) + + * Input: + * n = 4 + * arr = {10, 30, 5, 60} + * Output: 4500 + * Explanation: The matrices have dimensions + * 10*30, 30*5, 5*60. Say the matrices are A, B + * and C. Out of all possible combinations,the + * most efficient way is (A*B)*C. The + * number of multiplications are: 10*30*5 + 10*5*60 = 4500. + */ diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index ea677b45..9ca90940 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -18,6 +18,7 @@ 1. [Longest Common Subsequence](Dynamic-Programming/longest-common-subsequence.cpp) 2. [Longest Common Substring](Dynamic-Programming/longest-common-substring.cpp) 3. [0/1-knapsack](Dynamic-Programming/01-knapsack-bottom-up.cpp) +4. [Matrix chain Multiplication](Dynamic-Programming/matrix-chain-multiplication.cpp) ## Graphs @@ -60,7 +61,6 @@ 3. [Stack using Array](Stacks/stack-using-array.cpp) - ## Sorting 1. [Bubble Sort](Sorting/bubble-sort.cpp) @@ -106,4 +106,5 @@ 4. [Fibonacci Series](Maths/fibonaccci-series.cpp) # Recursion + 1. [Tower of Hanoi](Recursion/towerofHanoi.cpp)