Uva-348-Optimal Array Multiplication Sequence

来源:互联网 发布:没有windows update 编辑:程序博客网 时间:2024/05/01 18:00

求矩阵乘法的优化方案,使得乘的次数最少。

代码:

#include<cstdio>#include<cstring>#include<iostream>using namespace std;const int maxn=31;const int inf=1<<28;struct node{    int row;    int col;}a[maxn];int n,dp[maxn][maxn],p[maxn][maxn];void Print(int l,int r){    if(l==r)    {printf("A%d",l+1);return;    }    if(l<r)    {printf("(");Print(l,p[l][r]);printf(" x ");Print(p[l][r]+1,r);printf(")");    }    }int DP(int st,int ed){    if(st>=ed)return 0;    if(dp[st][ed])return dp[st][ed];    int ans=inf;    for(int i=st;i<ed;i++)    {if(ans>DP(st,i)+DP(i+1,ed)+a[st].row*a[i].col*a[ed].col){    ans=DP(st,i)+DP(i+1,ed)+a[st].row*a[i].col*a[ed].col;    p[st][ed]=i;}    }    dp[st][ed]=ans;    return ans;}int main(){    int cas=1;    while(scanf("%d",&n)&&n)    {memset(p,0,sizeof(p));memset(dp,0,sizeof(dp));for(int i=0;i<n;i++)    scanf("%d%d",&a[i].row,&a[i].col);DP(0,n-1);printf("Case %d: ",cas++);Print(0,n-1);printf("\n");    }    return 0;}