最优矩阵链乘

来源:互联网 发布:雅安数据恢复 编辑:程序博客网 时间:2024/05/13 00:33
</pre><pre name="code" class="cpp">#include <cstdio>#include <iostream>#include <cstring>#include <string>#include <map>#include <cmath>#define INF 1<<30using namespace std;int p[105],f[105][105];int min(int a, int b){    return a<b?a:b;}int main(){    int n;    while(~scanf("%d",&n)&&n)    {        for(int i=0; i<=n; i++)            cin>>p[i];        for(int i=1; i<=n; i++)        {            for(int j=0; j<=n; j++)                f[i][j]=INF;            f[i][i]=0;            f[i][i+1]=p[i-1]*p[i]*p[i+1];        }        for(int l=2; l<=n; l++)     ///递推的过程 记住要按照j-i递增的顺序递推            for(int i=1; i+l<=n; i++)                {                    int j=i+l;                    for(int k=i; k<=j; k++)                    f[i][j]=min(f[i][j],f[i][k]+f[k+1][j]+p[i-1]*p[k]*p[j]);                }        cout<<f[1][n]<<endl;    }    return 0;}


                                             
0 0