简单的矩阵连乘法,我是使用记忆化做的。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 11
#define INF 0x3f3f3f3f
typedef struct m_NODE {
int l, r;
}NODE;
NODE m[MAXN];
int mid_pos[MAXN][MAXN], dp[MAXN][MAXN];
void dfs(const int &l, const int &r)
{
if( l == r ) {
dp[l][r] = 0; return;
}
dp[l][r] = INF;
for(int k = l; k < r; k ++) {
if( -1 == dp[l][k] ) {
dfs(l, k);
}
if( -1 == dp[k+1][r] ) {
dfs(k+1, r);
}
if( dp[l][r] > dp[l][k]+dp[k+1][r]+m[l].l*m[r].r*m[k].r ) {
mid_pos[l][r] = k;
dp[l][r] = dp[l][k]+dp[k+1][r]+m[l].l*m[r].r*m[k].r;
}
}
}
void back_track(const int &l, const int &r)
{
if( l == r ) {
printf("A%d", l); return;
}
printf("(");
back_track(l, mid_pos[l][r]); printf(" x ");
back_track(mid_pos[l][r]+1, r); printf(")");
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int n, cas(1);
while( scanf("%d", &n) && n ) {
for(int i = 1; i <= n; i ++) {
scanf("%d %d", &m[i].l, &m[i].r);
}
memset(mid_pos, -1, sizeof(mid_pos));
memset(dp, -1, sizeof(dp)); dfs(1, n);
printf("Case %d: ", cas ++); back_track(1, n); printf("\n");
}
return 0;
}