标签:efi htm turn tip 个数 names 描述 关于 算法
问题描述:
具体可参考:https://blog.csdn.net/liufeng_king/article/details/8497607
代码如下:
#ifndef MATRIX_CHAIN_H #define MATRIX_CHAIN_H void matrix_chain(int *p, int n, int **m, int **s); void traceback(int i, int j, int **s); #endif
#include <iostream> #include "matrix_chain.h" using namespace std; //利用动态规划算法获取最优值 void matrix_chain(int *p, int n, int **m, int **s) //p:各个矩阵的列数,n:矩阵个数,m:m[i:j]矩阵i到j的相乘次数,s:对应的分开位置 { for (int i = 0; i < n; i++) { m[i][i] = 0; } for (int r = 2; r <= n; r++) { for (int i = 0; i < n - r + 1; i++) { int j = i + r - 1; m[i][j] = m[i + 1][j] + p[i - 1] * p[i] * p[j]; s[i][j] = i; for (int k = i + 1; 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; } } } } } //利用s[i][j]获取最优解 void traceback(int i, int j, int **s) { if (i == j) return; traceback(i, s[i][j], s); traceback(s[i][j] + 1, j, s); cout << "Multiply A" << i << " , " << s[i][j]; cout << "and A" << (s[i][j] + 1) << " , " << j << endl; }
#include <iostream> #include "matrix_chain.h" using namespace std; int main(void) { int matrix_num = 0; //矩阵个数 cout << "请输入矩阵个数:" << endl; cin >> matrix_num; int **m = new int *[matrix_num]; for (int i = 0; i < matrix_num; i++) m[i] = new int[matrix_num]; int **s = new int *[matrix_num]; for (int i = 0; i < matrix_num; i++) s[i] = new int[matrix_num]; int *p = new int[matrix_num]; cout << "请输入各矩阵的列数:" << endl; for (int i = 0; i < matrix_num; i++) { cin >> p[i]; } matrix_chain(p, matrix_num, m, s); traceback(0, matrix_num - 1, s); system("pause"); return 1; }
可结合我的另一篇关于贪心算法的博客进行比较,了解这两者的区别;
(http://www.cnblogs.com/zf-blog/p/8674932.html)
标签:efi htm turn tip 个数 names 描述 关于 算法
原文地址:https://www.cnblogs.com/zf-blog/p/8763090.html