矩阵连乘
作者:
NAGIoto
,
2024-05-10 20:20:16
,
所有人可见
,
阅读 4
int MatrixMul(vector<long long> p, vector<vector<long long>> &M, vector<vector<int>> &K)
{
// 确定联乘矩阵数量
int n = p.size() - 1;
// 分配结果表空间
M = vector<vector<long long>>(n, vector<long long>(n));
K = vector<vector<int>>(n, vector<int>(n));
// 从叶子结点自底向上推导最优值M,并记录计算轨迹K
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n - i; j++)
{
int k = j;
M[j][j + i] = /*M[j][k] +*/ M[k + 1][j + i] + p[j] * p[k + 1] * p[j + i + 1];
K[j][j + i] = k;
for (int k = j + 1; k < j + i; k++)
{
long long temp = M[j][k] + M[k + 1][j + i] + p[j] * p[k + 1] * p[j + i + 1];
if (temp < M[j][j + i])
{
M[j][j + i] = temp;
K[j][j + i] = k;
}
}
}
}
return 0;
}