矩阵链乘法(C++ 中的 O(N^3) 解决方案)
如果给定一个矩阵链,我们必须找到乘以正确顺序的最少矩阵数。
我们知道矩阵乘法是关联的,所以对于四个矩阵 ABCD,我们可以按顺序计算 A(BCD)、(AB)(CD)、(ABC)D、A(BC)D。像这样,我们的任务是找出哪种顺序高效乘法。
给定的输入中有数组 arr,包含 arr[] = {1, 2, 3, 4}。这意味着矩阵的顺序为 (1 x 2)、(2 x 3)、(3 x 4)。
输入 - 输入矩阵的顺序。{1, 2, 3, 4}。这意味着矩阵是
{(1 x 2), (2 x 3), (3 x 4)}.
输出 - 乘以这三个矩阵所需的最小操作数。本例中的结果为 18。
算法
matOrder(array, n) Input: List of matrices, the number of matrices in the list. Output: Minimum number of matrix multiplication. Begin define table minMul of size n x n, initially fill with all 0s for length := 2 to n, do for i:=1 to n-length, do j := i + length – 1 minMul[i, j] := ∞ for k := i to j-1, do q := minMul[i, k] + minMul[k+1, j] + array[i-1]*array[k]*array[j] if q < minMul[i, j], then minMul[i, j] := q done done done return minMul[1, n-1] End
示例
#include<iostream> using namespace std; int matOrder(int array[], int n){ int minMul[n][n]; //holds the number of scalar multiplication needed for (int i=1; i<n; i++) minMul[i][i] = 0; //for multiplication with 1 matrix, cost is 0 for (int length=2; length<n; length++){ //find the chain length starting from 2 for (int i=1; i<n-length+1; i++){ int j = i+length-1; minMul[i][j] = INT_MAX; //set to infinity for (int k=i; k<=j-1; k++){ //store cost per multiplications int q = minMul[i][k] + minMul[k+1][j] + array[i-1]*array[k]*array[j]; if (q < minMul[i][j]) minMul[i][j] = q; } } } return minMul[1][n-1]; } int main(){ int arr[] = {1, 2, 3, 4}; int size = 4; cout << "Minimum number of matrix multiplications: "<<matOrder(arr, size); }
输出
Minimum number of matrix multiplications: 18
广告