An introduction to the algorithm------------------matrix chain problem of dynamic programming

Source: Internet
Author: User

"Problem description"
Given the number of dimensions with n multiplicative matrices, it is required to calculate the number of multiplication times used in the optimal order of calculation, that is, the minimum number of multiplication times required for calculation. For example, the number of dimensions for a given three multiplicative matrices {a1,a2,a3} is 10*100,100*5 and 5*50, respectively, with (A1A2) A3, multiplied by 10*100*5+10*5*50=7500 times, A1 (A2A3), and multiplication times 100*5*50+ 10*100*50=75000 times multiplication, it is clear that the best order is (A1A2) A3, multiply 7,500 times.


Analysis:

matrix Chain multiplication problem Description:

Given a sequence consisting of n matrices [A1,a2,...,an], the product a1a2 ... An, find the parentheses method that minimizes multiplication times.

1) Looking for the best sub-structure

The hardest part of this problem is finding the optimal substructure. The Product a1a2 ... An arbitrary parenthesis method of an will divide the sequence somewhere in two parts, that is, where the last multiplication is calculated, we will write this position as K, that is to say first calculate A1 ... AK and ak+1...an, and then multiply the results of these two parts.

The optimal sub-structure is as follows: Suppose a1a2 ... An optimal parenthesis of the product is divided between AK and ak+1, then the prefix sub-chain A1 ... AK's parentheses must be A1 ... An optimal bracket for AK, the suffix strand is the same.

The exact location of K is not known at first, and all positions need to be traversed to ensure that the appropriate k is found to divide the product.

2) Construct recursive solution
Set M[I,J] for matrix chain AI ... The cost of the optimal solution of AJ is
┌0 If i = j
M[I,J] =

└min (i≤k<j) {m[i,k] + m[k+1,j] + p[i-1] * p[k] *p[j]} if i<j

3) build auxiliary tables to solve overlapping sub-problems
From the second step of recursion can be found in the process of the solution will have a lot of overlapping sub-problems, you can use a nxn-dimensional auxiliary table m[n][n] s[n][n] respectively, the optimal product price and its division position K.

Auxiliary table S[n][n] can be constructed from 2 methods, one is the bottom-up form construction, the method requires the incremental way to fill in the solution of the sub-problem, that is, the first calculation of the length of 2 of all matrix chain solution, and then calculate the length of the matrix chain 3, until the length of N; This method initializes each element of the table to a special value (the optimal product cost can be set to a maximum value in this problem) to indicate that the solution to the sub-problem encountered is to be filled in the recursive process.

Here I use C + + in the container to solve, the general use of the array subscript the problem is extremely easy to travel, or C + + more convenient, solve the array must use represented to represent the array subscript. No nonsense, the idea of the introduction of the algorithm in the tree to explain the principle of solving the problem of writing code is easy.

#include <iostream> #include <vector> #include <algorithm> #include <iterator>using namespace Std;pair<vector<vector<int>>,vector<vector<int>>> Matrix_chain_order (vector< Int> p) {int n = p.size ();vector<vector<int>> m (N, vector<int> (n, 0)); the vector of//vector is equivalent to an array of arrays,  That is, the two-dimensional array m[][]vector<vector<int>> s (n, vector<int> (n, 0));//Ibid. s[][]for (int len = 2; len < n; len++) {for (int i = 1; i < N-len + 1; ++i) {Int J = i + len-1;m[i][j] = 0x7fffffff;for (int k = i; k <= j-1; ++k) {int q = m[i][k] + m[k + 1][j] + p[i-1] * p[k ] * P[J];IF (Q < m[i][j]) {m[i][j] = q;s[i][j] = k;}}} Return Make_pair (M, s);} Print optimal solution void Print_optimal_parens (Vector<vector<int> > s, int i, int j) {if (i = = j) cout << "A" << I ; Else{cout << "(";p rint_optimal_parens (S, I, S[i][j]);p Rint_optimal_parens (S, s[i][j] + 1, j); cout << ")";}} General recursive method int Recursive_matrix_chain (vector<int> p, int i, int j) {int n = p.size ();vector<vector<int>> m (N, vector<int> (n, 0)); if (i = = j) return 0;m[i][j] = 0x7f  ffffff;for (int k = i; k < J; k++) {int q = Recursive_matrix_chain (P, I, K) +recursive_matrix_chain (p, K + 1, j) + P[i- 1] * p[k] * P[J];IF (Q < m[i][j]) m[i][j] = q;} return m[i][j];} The top-down recursive method with a memo implements INT Look_up_chain (vector<vector<int>> m, vector<int> p, int i, int j) {if (M[i][j] &lt ;  0X7FFFFFFF)//If M[I][J] is not infinity then the m[i][j] has been calculated by the lookupchain of the next layer return m[i][j];if (i = = j) M[i][j] = 0;for (int k = i; k < J;  k++) {int q = look_up_chain (M, p, I, K) +look_up_chain (M, p, K + 1, j) + p[i-1] * p[k] * P[J];IF (Q < m[i][j]) M[i][j] = q;} return m[i][j];} int Memoized_matrix_chain (vector<int> p,int s,int e) {int n = p.size ();vector<vector<int>> m (N, Vector <int> (n, 0)); for (int i = 1; i < n; i++) {for (int j = i; j < n; ++j) {m[i][j] = 0x7fffffff;}} Return Look_up_chain (M, p, S, e);} int main () {vector<int> p = {30, 35,5,};vector<vector<int>> m = Matrix_chain_order (p) .first;vector<vector<int>> s = m Atrix_chain_order (P). Second;cout << "vector m:" << endl;for (size_t i = 0; I < m.size (); i++) {copy (M[i].begin (), M[i].end (), ostream_iterator<int> (cout, "")); cout << Endl;} cout << "vector s:" << endl;for (size_t i = 0; I <s.size (); i++) {copy (S[i].begin (), S[i].end (), ostream_iterator<int> (cout, "")); cout << Endl;} cout << "Output optimal solution: ———— >";p rint_optimal_parens (S, 1, 6); cout << endl;cout << "----------------------- ---------------------------"<< Endl;  vector<vector<int>> m1 = Matrix_chain_order (p) .first;vector<int> p1 = {5, +--, +--+----+----};cout << "General Recursive Method Solution:"; cout << Recursive_matrix_chain (P1, 1, 6) << endl;cout << "Recursive Solution with Memo:"; cout <& Lt Look_up_chain (M1, P1, 1, 6) << Endl;}




An introduction to the algorithm------------------matrix chain problem of dynamic programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.