#include <iostream> #include <cstdlib> using namespace std; int matrixChainOrder(int p[], int n, int** m, int** s) { for(int i = 1; i <= n; i++) { m[i][i] = 0; } for(int l = 2; l <= n; l++) { for(int i = 1; i <= n-l+1; i++) { int j = i+l-1; m[i][j] = INT_MAX; for(int k = i; k <= j-1; k++) { int q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]; if(q < m[i][j]) { m[i][j] = q; s[i][j] = k; } } } } return m[1][n]; } int main() { int n = 3; int p[] = {8, 1, 8}; int** m = new int*[n+1]; int** s = new int*[n+1]; for(int i = 1; i <= n; i++) { m[i] = new int[n+1]; s[i] = new int[n+1]; } int minMultiplications = matrixChainOrder(p, n, m, s); cout << "The minimum number of multiplications is: " << minMultiplications << endl; cout << "The solutions to the subproblems are:" << endl; for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { cout << "(" << m[i][j] << ", " << s[i][j] << ") "; } cout << endl; } for(int i = 1; i <= n; i++) { delete[] m[i]; delete[] s[i]; } delete[] m; delete[] s; return 0; }请在此代码基础上稍加修改,避免输出的矩阵元素值异常大
时间: 2024-03-09 11:46:44 浏览: 55
这段代码存在一个问题,就是在未初始化数组 `m` 和 `s` 的值时,直接对其进行赋值操作,在这种情况下,它们的值是不确定的,可能会导致输出异常大的情况。因此,我们需要在对数组进行赋值操作之前,先将它们的值初始化为 0。
修改后的代码如下所示:
```cpp
#include <iostream>
#include <cstdlib>
using namespace std;
int matrixChainOrder(int p[], int n, int** m, int** s) {
// 初始化数组 m 和 s
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
m[i][j] = 0;
s[i][j] = 0;
}
}
for(int i = 1; i <= n; i++) {
m[i][i] = 0;
}
for(int l = 2; l <= n; l++) {
for(int i = 1; i <= n-l+1; i++) {
int j = i+l-1;
m[i][j] = INT_MAX;
for(int k = i; k <= j-1; k++) {
int q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if(q < m[i][j]) {
m[i][j] = q;
s[i][j] = k;
}
}
}
}
return m[1][n];
}
int main() {
int n = 3;
int p[] = {8, 1, 8};
int** m = new int*[n+1];
int** s = new int*[n+1];
for(int i = 1; i <= n; i++) {
m[i] = new int[n+1];
s[i] = new int[n+1];
}
int minMultiplications = matrixChainOrder(p, n, m, s);
cout << "The minimum number of multiplications is: " << minMultiplications << endl;
cout << "The solutions to the subproblems are:" << endl;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
cout << "(" << m[i][j] << ", " << s[i][j] << ") ";
}
cout << endl;
}
for(int i = 1; i <= n; i++) {
delete[] m[i];
delete[] s[i];
}
delete[] m;
delete[] s;
return 0;
}
```
修改后的代码会对数组 `m` 和 `s` 进行初始化,初始化后再进行赋值操作,从而避免输出异常大的矩阵元素值。
阅读全文