Algorithm Design, dynamic planning, matrix, and multiplication
//////////////////////////////////////// ////////////////////////
// TITLE: matrix concatenation Problem
// EDITOR: Xiaoqiao streamline
// DADE: 2008.11.16
// TOOL: Microsoft Visual Studio 2008
//////////////////////////////////////// ////////////////////////
# Include <iostream>
Usingnamespace std;
// Calculate the optimal value
VoidMatrixChain (int * p, intn, int ** m, int ** s)
{
For (inti = 1; I <= n; I ++)
{
M [I] [I] = 0;
}
For (intr = 2; r <= n; r ++)
{
For (inti = 1; I <= n-r + 1; I ++)
{
Int j = I + R-1;
M [I] [j] = m [I + 1] [j] + p [I-1] * p [I] * p [j];
S [I] [j] = I;
For (intk = I + 1; k <j; k ++)
{
Int t = m [I] [k] + m [k + 1] [j] + p [I-1] * p [k] * p [j];
If (t <m [I] [j])
{
M [I] [j] = t;
S [I] [j] = k;
}
}
}
}
}
// Construct the optimal solution
VoidTraceback (inti, intj, int *** s)
{
If (I = j)
Return;
Traceback (I, s [I] [j], s );
Traceback (s [I] [j] + 1, j, s );
Cout <"Multiply A" <I <"," <s [I] [j];
Cout <"and A" <s [I] [j] + 1 <"," <j <endl;
}
Intmain ()
{
Int N, * P, ** M, ** S;
Cout <"Number of input matrices N :";
Cin> N;
P = new int [N + 1]; // allocates space for the dimension of the matrix.
M = new int * [N + 1]; // dynamically allocates space for the two-dimensional array M
For (inti = 0; I <= N; I ++)
{
M [I] = new int [N + 1];
}
S = new int * [N + 1]; // The second that records the optimal disconnection location
// Dimension Array S dynamically allocates Space
For (inti = 0; I <= N; I ++)
{
S [I] = new int [N + 1];
}
For (inti = 0; I <= N; I ++)
{
Cin> P [I];
}
Www.2cto.com
MatrixChain (P, N, M, S );
Traceback (1, N, S );
// Release the dynamically allocated space
Delete [] P;
For (inti = 0; I <= N; I ++)
{
Delete M [I];
M [I] = NULL;
}
Delete [] M;
M = NULL;
For (inti = 0; I <= N; I ++)
{
Delete S [I];
S [I] = NULL;
}
Delete [] S;
S = NULL;
Return 0;
}
Author; baitxaps