• 算法导论15.2节 矩阵链乘法


    View Code
    #include <stdio.h>
    #include <string.h>
    
    #define SIZE 6
    
    typedef struct MATRIX {
            int row;
            int col;
    }matrix;
    
    int m[SIZE][SIZE] = {0};
    int s[SIZE][SIZE] = {0};
    
    void matrixChainOrder(matrix *p)
    {
            int i, j, l, k;
            int n = 6;//sizeof(p)/sizeof(matrix);
            for (i = 0; i < n; i++) {
                    m[i][i] = 0;
            }
            for (l = 2; l <= n ; l++) {
                    for (i = 0; i < n-l+1; i++) {
                            j = i + l - 1;
                            m[i][j] = 0x7fffffff;//开始设置为0xffffffff为-1
                            for (k = i; k <= j; k++) {
                                    int q = m[i][k] + m[k+1][j] + (p[i].row) * (p[k].col) * (p[j].col);
                                    if (q < m[i][j]) {
                                            m[i][j] = q;
                                            s[i][j] = k+1;
                                    }
                            }
                    }
            }
    }
    
    void printOptimalParent(int (*s)[6], int i, int j)
    {
            if (i == j) {
                    printf("A%d", i);
            }
            else {
                    printf("(");
                    printOptimalParent(s, i, s[i-1][j-1]);
                    printOptimalParent(s, s[i-1][j-1]+1, j);
                    printf(")");
            }
    }
    int main()
    {
            matrix matrix[6] = {{30,35}, {35, 15}, {15, 5}, {5, 10}, {10, 20}, {20, 25}};
            matrixChainOrder(matrix);
            printOptimalParent(s, 1, 6);
            printf("\n");
            return 0;
    }
  • 相关阅读:
    IntelliJ Idea使用代码折叠
    c# 文件属性读取操作及文件之间操作
    c#文件操作
    c++头文件 #include<iostream>
    基本SQL语句
    dd
    c#属性中的get和set属性
    c#
    c#运算表达式
    c#方法
  • 原文地址:https://www.cnblogs.com/taotao315/p/2958216.html
Copyright © 2020-2023  润新知