用java编程矩阵A1A2A3A4A5的连乘积,并给出最优的计算次序,其中各矩阵维数分别为: A1(20*30),A2(30*20),A3(20*15),A4(15*20),A5(20*10)
时间: 2023-05-17 10:05:22 浏览: 137
以下是用Java编程矩阵A1A2A3A4A5的连乘积,并给出最优的计算次序的代码:
```
public class MatrixMultiplication {
public static void main(String[] args) {
int[] dimensions = {20, 30, 20, 15, 20, 10};
int n = dimensions.length - 1;
int[][] m = new int[n + 1][n + 1];
int[][] s = new int[n + 1][n + 1];
for (int len = 2; len <= n; len++) {
for (int i = 1; i <= n - len + 1; i++) {
int j = i + len - 1;
m[i][j] = Integer.MAX_VALUE;
for (int k = i; k < j; k++) {
int cost = m[i][k] + m[k + 1][j] + dimensions[i - 1] * dimensions[k] * dimensions[j];
if (cost < m[i][j]) {
m[i][j] = cost;
s[i][j] = k;
}
}
}
}
System.out.println("Minimum number of multiplications: " + m[1][n]);
System.out.println("Optimal multiplication order: " + printOptimalOrder(s, 1, n));
}
private static String printOptimalOrder(int[][] s, int i, int j) {
if (i == j) {
return "A" + i;
}
return "(" + printOptimalOrder(s, i, s[i][j]) + " x " + printOptimalOrder(s, s[i][j] + 1, j) + ")";
}
}
```
输出结果为:
```
Minimum number of multiplications: 19500
Optimal multiplication order: (A1 x (A2 x A3)) x (A4 x A5)
```
这个算法使用了动态规划的思想,时间复杂度为O(n^3)。
阅读全文