Given a sequence (chain) consisting of n matrices to be multiplied <A1, A2, A3 ,......., an>, calculate the product A1A2 ..... an. A matrix is enclosed in parentheses. Brackets in the matrix chain have a great impact on the operation performance.
Only when two matrices A and B are compatible (that is, the number of columns of A is equal to the number of rows of B) Can we perform the multiplication operation. If A is A p x q matrix, B is A q X r matrix, and C is A matrix of p X r. The time for calculating C is determined by the number of multiplication operations. The number of times is p × q × r.
The matrix chain multiplication problem can be expressed as: A chain consisting of a given n matrices <A1, A2, a3 ......., an>, where I = 1, 2, 3, 4 ....., n, the dimension of matrix Ai is Pi-1 × Pi, the product A1A2A3 ..... an. All parentheses are added in the form of a minimum scalar multiplication.
For AiAi + 1 ....... all the brackets of Aj form separate the product between Ak and Ak + 1, that is, the computing matrix Ai... k and Ak + 1 ..... aj, then multiply them to get the final product of Ai ....... j. the price of brackets is Ai... k and Ak + 1... j.
Recursive definition with the minimum price of All parentheses:
M [I, j] = min {m [I, k] + m [k + 1, j] + Pi-1 * Pk * Pj}; I <j; m [I, j] = 0; I = j;
When calculating the optimal cost, use the auxiliary table m [n] [n] To save m [I] [j], use s [n] [n] to record the K value at the optimal cost obtained when m [I] [j] is calculated, that is, every table item s [I] [j] records the product AiAi + 1 ...... the K value obtained by Aj during the split between Ak and Ak + 1 is the best value when all parentheses are added.
The Code is as follows:
[Cpp]
// The maximum number of scalar multiplication required to calculate the matrix chain Product
Void MATRIX_CHAIN_ORDER (int PArray [], int m [] [PArrayLength], int s [] [PArrayLength], int Length)
{
Int n = Length-1; // represents the multiplication of n matrices.
Int temp = 0; // Temporary Variable
For (int I = 1; I <Length; I ++)
{
M [I] [I] = 0; // first, the cost is initialized to 0; the minimum cost of a chain with a length of 1 is 0.
}
For (int l = 2; l <= n; l ++) // the length of the second chain is calculated as 2, 3, and ,.. Minimum Cost of n chains
{
For (int I = 1; I <= n-l + 1; I ++)
{
Int j = I + L-1;
M [I] [j] = 0x7fffffff;
For (int k = I; k <j; k ++) // test the k value one by one to find the k value at the minimum cost.
{
Temp = m [I] [k] + m [k + 1] [j] + PArray [I-1] * PArray [k] * PArray [j];
If (temp <m [I] [j])
{
M [I] [j] = temp;
S [I] [j] = k;
}
}
}
}
}
// Construct an optimal solution
Void PRINT_OPTIMAL_PARENS (int s [] [PArrayLength], 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 <")";
}
}
Result: