using System ;
using System . Collections . Generic ;
namespace SDProject
{
public class MartixMultiply
{
private List < Martix > MList ;
public MartixMultiply ()
{
initial ();
}
private void initial ()
{
Martix m1 = new MartixMultiply . Martix ( 2 , 5 );
Martix m2 = new MartixMultiply . Martix ( 5 , 100 );
Martix m3 = new MartixMultiply . Martix ( 100 , 4 );
Martix m4 = new MartixMultiply . Martix ( 4 , 50 );
Martix m5 = new MartixMultiply . Martix ( 50 , 6 );
Martix [] array ={ m1 , m2 , m3 , m4 , m5 };
this . MList = new List < Martix >( array );
}
int [,] M = new int [ 5 , 5 ];
public void GetBestSolutionByDP ()
{
// 设局部最优解是 M 【 i , j 】设矩阵 Ai 的维数是 P(i-1), 和 P(i)
// 则 M 【 i , j 】 =min{M 【 i , k 】 +M 【 k+1,j 】 +P(i-1)*P(k)*P(j)} 其中 i<=k<j
for ( int i = 0 ; i < 5 ; i ++)
for ( int j = 0 ; j < 5 ; j ++)
{
if ( j <= i )
{
M [ i , j ]= 0 ;
}
else
{
M [ i , j ]= Int32 . MaxValue ;
}
}
int finalResult = getOpt ( 0 , 4 );
Console . WriteLine ( finalResult );
}
private int getOpt ( int from , int to )
{
int costform2K ;
int costK2to ;
int costMultiply2 ;
int costTotal = Int32 . MaxValue ;
if ( M [ from , to ]!= Int32 . MaxValue )
{
return M [ from , to ];
}
else
{
for ( int k = from ; k < to ; k ++)
{
costform2K = getOpt ( from , k );
costK2to = getOpt ( k + 1 , to );
costMultiply2 = MList [ from ]. orderX * MList [ k ]. orderY * MList [ to ]. orderY ;
int tempcost = costform2K + costK2to + costMultiply2 ;
if ( costTotal > tempcost )
{
costTotal = tempcost ;
M [ from , to ]= tempcost ;
}
}
return costTotal ;
}
}
class Martix
{
public Martix ( int x , int y )
{
orderX = x ;
orderY = y ;
}
public int orderX { set ; get ;}
public int orderY { set ; get ;}
}
}
}
本文介绍了一种使用动态规划解决矩阵链乘法问题的方法,通过计算不同矩阵组合的最小代价来找到最优乘法顺序。
1630

被折叠的 条评论
为什么被折叠?



