最大矩阵连乘次数
这题只不过把王晓东书上求最小连乘次数改为了求最大连乘次数,方法还是DP
状态转移方程:m[i][j] = Max(m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j])
#include <stdio.h>
#define N 11
int m[N][N] , p[N+1] , n;
int MatrixChain()
{
int r , i , j , k , t;
for(i = 1 ; i <= n ; i++) m[i][i] = 0;
for(r = 2 ; r <= n ; r++)
{
for(i = 1 ; i <= n - r + 1 ; i++)
{
j = i + r - 1;
m[i][j] = m[i+1][j] + p[i-1] * p[i] * p[j];
for(k = i + 1 ; k < j ; k++)
{
t = m[i][k] + m[k+1][j] + p[i-1] * p[k] * p[j];
m[i][j] = t < m[i][j] ? m[i][j] : t;
}
}
}
return m[1][n];
}
int main(void)
{
int z , i;
scanf("%d", &z);
while(z-- > 0)
{
scanf("%d", &n);
for(i = 0 ; i <= n ; i++)
scanf("%d", p + i);
printf("%d\n", MatrixChain());
}
return 0;
}