Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用DP解释链式矩阵乘法?_C_Algorithm_Dynamic Programming_Matrix Multiplication - Fatal编程技术网

C 使用DP解释链式矩阵乘法?

C 使用DP解释链式矩阵乘法?,c,algorithm,dynamic-programming,matrix-multiplication,C,Algorithm,Dynamic Programming,Matrix Multiplication,我无法理解算法书中给出的优化链式矩阵乘法(使用DP)代码示例 int MatrixChainOrder(int p[], int n) { /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[n][n]; int

我无法理解算法书中给出的优化链式矩阵乘法(使用DP)代码示例

int MatrixChainOrder(int p[], int n)
{

    /* For simplicity of the program, one extra row and one extra column are
       allocated in m[][].  0th row and 0th column of m[][] are not used */
    int m[n][n];

    int i, j, k, L, q;

    /* m[i,j] = Minimum number of scalar multiplications needed to compute
       the matrix A[i]A[i+1]...A[j] = A[i..j] where dimention of A[i] is
       p[i-1] x p[i] */

    // cost is zero when multiplying one matrix.
    for (i = 1; i < n; i++)
        m[i][i] = 0;

    // L is chain length.  
    for (L=2; L<n; L++)   
    {
        for (i=1; i<=n-L+1; i++)
        {
            j = i+L-1;
            m[i][j] = INT_MAX;
            for (k=i; k<=j-1; k++)
            {
                // q = cost/scalar multiplications
                q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
                if (q < m[i][j])
                    m[i][j] = q;
            }
        }
    }

    return m[1][n-1];
}
intmatrixchainoder(intp[],intn)
{
/*为了简化程序,需要增加一行和一列
在m[][]中分配。不使用m[][]的第0行和第0列*/
int m[n][n];
int i,j,k,L,q;
/*m[i,j]=计算所需的最小标量乘法数
矩阵A[i]A[i+1]…A[j]=A[i..j],其中A[i]的维数为
p[i-1]x p[i]*/
//当乘以一个矩阵时,成本为零。
对于(i=1;i简而言之,这些都是将值保持在给定边界内的限制。

在自下而上,也就是DP中,我们首先尝试解决最小可能的情况(我们解决每个最小的情况)。现在,当我们考虑重复性时(m[i,j]表示从i,j……到父母的成本)

我们可以看到,对于p(n),最小可能的解决方案(任何其他较大的子问题都需要)的长度小于我们需要解决的长度。。我们需要为长度小于n的表达式创建父表达式的所有成本。这导致我们纵向解决问题。。。(注:外环中的l表示我们试图优化其成本的段的长度)

现在我们首先解决长度为1的所有子问题,即始终为0(不需要乘法)

现在你的问题是L=2->L=n 我们将长度从2变为n只是为了解决子问题,以便

i是所有子区间的起点,因此它们可以是长度为l的区间的起点


自然地,j代表子区间的终点->i+l-1是子区间的终点(因为我们知道起始点和长度,我们可以计算出子区间的终点)

hi Shubham,i+l-1怎么不大于n?这就是我到目前为止所理解的,我们在不同长度的链中循环(假设给定的总长度为8),所以我们找到了不同组合的最优解,即2,6 | 3,5 | 4,4。这就是我去(n-L+1)的原因?因为我们将原始的8分为2个子问题?现在当我们加上(n-L+1+L-1)即i+L-1时,我们得到j=n。因此没有j将永远不会超过n。我们正在除以M[i,j]分为几个子问题,并从中获得最佳结果…请参见重复或参考()