程序碎片- 矩阵乘法优化(dp,递归)

本文介绍了一种使用动态规划解决矩阵链乘法问题的方法,通过计算不同矩阵组合的最小代价来找到最优乘法顺序。

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 ;}

       }

    }

}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值