矩阵连乘积问题
分治递归 消耗指数时间
子问题重复计算
子问题个数
递归 从上至下 大问题分解成小问题
动态规划 自底向上 从最小子问题逐层向上合成最大问题
第一步 求最小子问题 i==j
第二步 2 到 n 最优的m[i,j] 求min
保存s[i,j]
#include<iostream>
#include<cstring>
using namespace std;
#define NUM 51
int main(){
int n = 6;
int m[n+1][n+1];
int s[n + 1][n + 1];
memset(m, 0, sizeof(m));
memset(s, 0, sizeof(s));
int p[7] = {50, 10, 40, 30, 5, 20, 15};
for (int i = 1; i <= n; i++)
{
m[i][i] = 0;
}
cout << endl;
for (int r = 2; r <= n; r++)
{
int j=r;
for (int i = 1; i <= n - r + 1; i++)
{
m[i][j] = m[i][i]+m[i+1][j]+p[i-1]*p[i]*p[j];
s[i][j] = i;
for (int k = i; k < j; k++){
int t = m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if (t < m[i][j]) {
m[i][j] = t;
s[i][j] = k;
}
}
j++;
}
cout << endl;
}
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
cout << m[i][j] << " ";
}
cout << endl;
}
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
cout << s[i][j] << " ";
}
cout << endl;
}
return 0;
}
递归实现矩阵连乘
#include<iostream>
#include<cstring>
using namespace std;
int s[100][100];
int p[100];
int m[100][100];
int Recurve(int i, int j)
{
int n;
if(i==j){
return 0;
}
m[i][j] = Recurve(i, i) + Recurve(i+1, j) + p[i - 1] * p[i] * p[j];
s[i][j] = i;
for (int k = i+1; k < j;k++){
n = Recurve(i, k) + Recurve(k+1, j) + p[i - 1] * p[k] * p[j];
if(n<m[i][j]){
m[i][j] = n;
s[i][j] = k;
}
}
return m[i][j];
}
// int Recurve(int i, int j){
// if (i == j){
// return 0;
// }
// int u = Recurve(i, i)+Recurve(i+1,j)+p[i-1]*p[i]*p[j];
// s[i][j] = i;
// for (int k = i+1; k<j; k++) {
// int t = Recurve(i, k) + Recurve(k+1,j)+p[i-1]*p[k]*p[j];
// if (t<u)
// {
// u = t; s[i][j] = k;
// }
// }
// m[i][j] = u;
// return u;
// }
int main(){
int n = 6;
memset(m, 0, sizeof(m));
memset(s, 0, sizeof(s));
for (int i = 0; i <= n; i++){
cin >> p[i];
}
cout << Recurve(1, n) <<endl;
cout << m[1][n] <<endl;
for (int i = 1; i <= n;i++){
for (int j = 1; j <= n;j++){
cout << m[i][j] << " ";
}
cout << endl;
}
for (int i = 1; i <= n;i++){
for (int j = 1; j <= n;j++){
cout << s[i][j] << " ";
}
cout << endl;
}
return 0;
}