去掉注释#define TESTMODE
取消随机输入模式
状态转移方程:m[i][j]=min(m[i][k]+m[k+1][j]+d(i-1)d(i)d(j))
其中m[i][j]是计算Ai … Aj所需要的最小乘法次数;
A: a×b 与B:b×c相乘,需要做的乘法总数为abc
时间复杂度分析(基本操作的次数,即比较的次数):
状态图:
m[1][1]
m[1][2] m[2][2]
m[1][3] m[2][3] m[3][3]
…
m[1][n] m[2][n] … m[n][n]
其中,计算m[i][j]需要比较j-i次,故可以算出,
#define TESTMODE
#include<iostream>
#include<ctime>
using namespace std;
const int inf = 1e9;
void segment(int** s, int i, int j)
{
if (i == j)cout << "A" << i;
else if (j - i == 1)cout << "A" << i << " * A" << j;
else
{
int mid = s[i][j];
if (mid == i)
{
segment(s, i, mid);
cout << " * ";
}
else
{
cout << "(";
segment(s, i, mid);
cout << ") * ";
}
if (j - mid == 1) segment(s, mid + 1, j);
else
{
cout << "(";
segment(s, mid + 1, j);
cout << ")";
}
}
}
void dp(int n, int* d)
{
int** m, ** s;
m = new int* [n + 1], s = new int* [n + 1];
for (int i = 0; i <= n; ++i)m[i] = new int[n + 1], s[i] = new int[n + 1];
for (int j = 1; j <= n; ++j)
{
for (int i = j; i >= 1; --i)
{
if (i == j) { m[i][j] = 0; continue; }
m[i][j] = inf;
for (int k = i; k < j; ++k)
{
if (m[i][j] > m[i][k] + m[k + 1][j] + d[i - 1] * d[j] * d[k])
{
m[i][j] = m[i][k] + m[k + 1][j] + d[i - 1] * d[j] * d[k];
//cout << i << ' ' << j << ' '<<k<<' ' << m[i][j] << endl;
s[i][j] = k;
}
}
}
}
cout << "Minimum is " << m[1][n] << endl;
cout << "The segmentation result is: \n";
segment(s, 1, n);
cout << endl;
delete[]m;
delete[]s;
}
int main()
{
#ifdef TESTMODE
int n;
cout << "PLS enter the number of matrixs:\n";
cin >> n;
srand(time(0));
int* d = new int[n + 1];
for (int i = 0; i <= n; ++i)d[i] = rand() % 10 + 1;
for (int i = 1; i <= 10 && i <= n; ++i)cout << "A" << i << ": " << d[i - 1] << " * " << d[i] << endl;
if (n > 10)cout << "...\n";
cout.put('\n');
dp(n, d);
delete[]d;
#else
int n;
cout << "PLS enter the number of matrixs:\n";
cin >> n;
int* d = new int[n + 1];
cout << "PLS enter the dimensions of the matrixs:\n\t(input " << n + 1 << " numbers, (i-1)th and ith numbers stand for the size of Matrix i)\n";
for (int i = 0; i <= n; ++i)cin >> d[i];
dp(n, d);
delete[]d;
#endif // TESTMODE
return 0;
}