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