• 算法导论15章矩阵链实现(c++)


     1 #include "stdafx.h"
     2 #include <iostream>
     3 #include <math.h>
     4 
     5 using namespace std;
     6 
     7 #define N 7
     8 #define INFINITY 100000000;
     9 
    10 int m[N-1][N-1];
    11 int s[N-1][N-1];
    12 void Matrix_chain_order (int p[])//特别容易搞错边界,这种写法不好
    13 {
    14     for (int i = 0; i < N - 1; i++)
    15         m[i][i] = 0;
    16     for (int l = 2; l < N; l++)
    17         for (int i = 0; i < N - l; i++)
    18         {
    19             int j = i + l - 1;
    20             m[i][j] = INFINITY;
    21             for (int k = i; k < j; k++)
    22             {
    23                 int q = m[i][k] + m[k+1][j] + p[i]*p[k+1]*p[j+1];
    24                 if (q < m[i][j])
    25                 {
    26                     m[i][j] = q;
    27                     s[i][j] = k;
    28                 }
    29             }
    30         }    
    31     return;
    32 }
    33 
    34 void Print_optimal_parens (int i, int j)//打印输出最优
    35 {
    36     if(i==j)
    37         cout<<"A["<<i<<"]";
    38     else
    39     {    cout<<"(";
    40         Print_optimal_parens (i,s[i][j]);
    41         Print_optimal_parens (s[i][j]+1,j);
    42         cout<<")";
    43     }
    44 }
    45 int main()
    46 {
    47     int p[N] = {30, 35, 15, 5, 10, 20, 25};
    48     Matrix_chain_order (p);
    49     Print_optimal_parens (0,5);
    50     system("pause");
    51     return 0;
    52 }
  • 相关阅读:
    Python脚本文件(.py)打包为可执行文件(.exe)即避免命令行中包含Python解释器
    MVC 三步完成增删改查设计
    MVC中使用SqlServerCe
    回车转Tab
    动态代码
    Mvc 用户没有登录跳转到登录界面
    Mvc
    Mvc提交
    EF查询 linq
    EF数据迁移 Migrations
  • 原文地址:https://www.cnblogs.com/kiss31415926/p/2984936.html
Copyright © 2020-2023  润新知