Chapter 2 dynamic planning -- matrix chain Multiplication

Source: Internet
Author: User
Tags scalar

Preface:Today, I am going to learn about the dynamic planning algorithm and how to use dynamic planning to analyze and solve the matrix chain multiplication problem. First, let's review the matrix multiplication method and give the C ++ language implementation process. Then, the dynamic planning algorithm is used to analyze the matrix chain multiplication problem and the C language implementation process is given.

1. Matrix MultiplicationFrom the definition, we can see that: Only when the MatrixAColumns and MatricesBWhen the number of rows is equalA×BMake sense. OneM×RMatrix A is left by oneRX n matrixB, You will getM×NMatrix C. In a computer, a matrix is a two-dimensional array. A matrix of m rows and R columns can be multiplied by a matrix of n columns of R rows. The result is a matrix of n columns of m rows, the number at the position of column J in row I equals to the number of R in row I in the previous matrix and the number of R in column J in the next matrix. Then, all r products are multiplied. and. The C ++ language is used to implement the complete multiplication of two matrices. The procedure is as follows:
#include<iostream>#include<cstdlib>using namespace std;#define A_ROWS        3#define A_COLUMNS     2#define B_ROWS        2#define B_COLUMNS     3void matrix_multiply(int A[A_ROWS][A_COLUMNS],int B[B_ROWS][B_COLUMNS],int C[A_ROWS][B_COLUMNS]){    if(A_COLUMNS!=B_ROWS)    {        cout<<"incompatible dimensions"<<endl;        exit(1);    }    int i,j,k;    for(i=0;i<A_ROWS;i++)        for(j=0;j<B_COLUMNS;j++)    {        C[i][j]=0;        for(k=0;k<A_COLUMNS;k++)            C[i][j]+=A[i][k]*B[k][j];    }}int main(){    int C[A_ROWS][B_COLUMNS];    int A[A_ROWS][A_COLUMNS]={{1,2},{3,4},{5,6}};    int B[B_ROWS][B_COLUMNS]={1,2,3,4,5,6};    matrix_multiply(A,B,C);    int i,j;    for(i=0;i<A_ROWS;i++)    {        for(j=0;j<B_COLUMNS;j++)            cout<<C[i][j]<<" ";        cout<<endl;    }}

2. Matrix chain multiplication problem description

A chain composed of N matrices <A1, A2, A3 ,....... an>, where I = 1, 2 ,... n, the dimension of matrix A is pi-1pi, the product a1a2... an is used to add all parentheses in a way that minimizes the number of scalar multiplication.

Note: In the matrix chain multiplication problem, the matrix is not actually multiplied to determine a matrix multiplication order with the minimum cost. Find such a combination order to minimize the cost of multiplication.

3. dynamic planning and analysis process

1) optimize the structure of All parentheses

The first step of dynamic planning is to find an optimal sub-structure. Suppose we want to calculate AIAI + 1 .... calculate the value of AJ... during the J process, a certain K value (I <= k <j) will... J is divided into two parts, making AI... J has the smallest amount of computing. It is divided into two subproblems: AI... K and aK + 1... J. You need to recursively find the optimal solutions for these two subproblems.

The optimal sub-structure can be analyzed as follows:Suppose AIAI + 1 .... an Optimal braces of AJ separate the product between AK and aK + 1, then AI .. K and aK + 1 .. J is also the best brackets.

2) a recursive Solution

Set M [I, j] to the minimum number of scalar multiplication operations required by computer matrix AI... J. The minimum cost for calculating A1. N is m [1, N]. Now we need to recursively define M [I, j]. The following two cases are discussed:

When I = J: M [I, j] = 0 (only one matrix is included)

When I <J: Find a K (I ≤ k <j) value from step 1, so that M [I, j] = min {M [I, k] + M [k + 1, J] + pi-1pkpj} (I ≤ k <j ).

3) Calculate the optimal cost

Although the process of recursive solution is given, it is not implemented using recursion. Instead, it is implemented using a bottom-up table through the help space. Let the dimension of matrix AI be pi-1pi, I = 1, 2... n. Input sequence: P = <P0, P1,... PN>, length [p] = n + 1. Use M [N] [N] To save the cost of M [I, j], s [N] [N] To save the calculation M [I, j] to obtain the value K at the optimal cost. Finally, we can use records in S to construct an optimal solution. The pseudocode of the computing process is provided in the book. The excerpt is as follows:

MAXTRIX_CHAIN_ORDER(p)  n = length[p]-1;  for i=1 to n      do m[i][i] = 0;  for t = 2 to n  //t is the chain length       do for i=1 to n-t+1                     j=i+t-1;                     m[i][j] = MAXLIMIT;                     for k=i to j-1                            q = m[i][k] + m[k+1][i] + qi-1qkqj;                            if q < m[i][j]                               then m[i][j] = q;                                    s[i][j] = k;  return m and s;

C ++ code:

#include<iostream>using namespace std;#define N 6#define MAXVALUE 100000000void matrix_chain_order(int *p,int m[N+1][N+1],int s[N+1][N+1]){    int i,j,l,k;    for(i=1;i<=N;i++)        m[i][i]=0;    for(l=2;l<=N;l++)    {        for(i=1;i<=N-l+1;i++)        {            j=i+l-1;            m[i][j]=MAXVALUE;            for(k=i;k<=j-1;k++)            {                int temp=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];                if(temp<m[i][j])                {                    m[i][j]=temp;                    s[i][j]=k;                }            }        }    }}void print_optimal_parens(int s[N+1][N+1],int i,int j){    if(i==j)        cout<<"A"<<i;    else    {        cout<<"(";        print_optimal_parens(s,i,s[i][j]);        print_optimal_parens(s,s[i][j]+1,j);        cout<<")";    }}int main(){    int p[N+1] = {30,35,15,5,10,20,25};    int m[N+1][N+1]={0};    int s[N+1][N+1]={0};    int i,j;    matrix_chain_order(p,m,s);    cout<<"m value is: "<<endl;    for(i=1;i<=N;++i)    {        for(j=1;j<=N;++j)            cout<<m[i][j]<<" ";        cout<<endl;    }    cout<<"s value is: "<<endl;    for(i=1;i<=N;++i)    {        for(j=1;j<=N;++j)            cout<<s[i][j]<<" ";        cout<<endl;    }    cout<<"The result is:"<<endl;    print_optimal_parens(s,1,N);    return 0;}

Chapter 2 dynamic planning -- matrix chain Multiplication

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.