Introduction to algorithms Chapter 15-matrix chain Multiplication

Source: Internet
Author: User

For detailed analysis, see Chapter 15th of Introduction to algorithms. The Code is as follows:
[Cpp]
# Include <iostream>
Using namespace std;
// P is the matrix chain, p [0], p [1] represents the first matrix, p [1], p [2] represents the second matrix, and length is the length of p
// If there are six matrices, length = 7, m is the two-dimensional matrix that stores the optimal results, t is
// Two-dimensional matrix
Void MatrixChainOrder (int * p, int (* m) [10], int (* t) [10], int length)
{
Int n = length-1;
Int I, j, k, q, num = 0;
// A [I] [I] has only one matrix, so the number of times of multiplication is 0, that is, m [I] [I] = 0;
For (I = 1; I <length; I ++)
{
M [I] [I] = 0;
}
// I indicates the length of the matrix chain. I = 2 indicates how to divide two matrices when they are multiplied.
For (I = 2; I <= n; I ++)
{
// J indicates that the division of the I matrix starting from the j matrix is optimal.
For (j = 1; j <= n-I + 1; j ++)
{
// K indicates how to divide the I matrix between them from j to k.
K = j + I-1;
// M [j] [k] stores the optimal results from j to k using the optimal division.
M [j] [k] = 0x7fffffff;
// Q is the number between j and K-1, the objective is to use q to divide the matrix between j and k,
// To find the optimal division, which is a test of experience.
For (q = j; q <= K-1; q ++)
{
Num = m [j] [q] + m [q + 1] [k] + p [J-1] * p [q] * p [k];
If (num <m [j] [k])
{
M [j] [k] = num;
T [j] [k] = q;
}
}
}
}
}
Void PrintAnswer (int (* t) [10], int I, int j)
{
If (I = j)
{
Cout <"A" <I;
}
Else
{
Cout <"(";
PrintAnswer (t, I, t [I] [j]);
PrintAnswer (t, t [I] [j] + 1, j );
Cout <")";
}
}
Int main ()
{Www.2cto.com
Int p [7] = {30, 35, 15, 5, 10, 20, 25 };
Int m [10] [10], t [10] [10];
MatrixChainOrder (p, m, t, 7 );
PrintAnswer (t, 1, 6 );
Return 0;
}
Author: liuzhanchen1987

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.