最优矩阵链乘 算法导论上有
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define inf 1000000000000000
//矩阵链乘
int p[12];
long long dp[12][12];
int s[12][12];
void printf_path(int i, int j)
{
if (i == j)
{
printf("A%d", i);
return;
}
printf("(");
printf_path(i, s[i][j]);
printf(" x ");
printf_path(s[i][j] + 1, j);
printf(")");
}
int main()
{
int ca = 1;
int n;
while (scanf("%d", &n) == 1 && n)
{
for (int i = 1; i <= n; i++)
scanf("%d %d", &p[i - 1], &p[i]);
for (int i = 1; i <= n; i++)
dp[i][i] = 0;
for (int l = 2 ; l <= n; l++)
for (int i = 1; i <= n - l + 1; i++)
{
int j = i + l - 1;
dp[i][j] = inf;
for (int k = i; k <= j - 1;k++)
{
int jia = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j];
if (dp[i][j] > jia)
{
dp[i][j] = jia;
s[i][j] = k;
}
}
}
printf("Case %d: ", ca++);
printf_path(1, n);
puts("");
}
return 0;
}