Matrix Chain Order
More...
#include <assert.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
|
int | matrixChainOrder (int l, const int *p, int *s) |
| for assert
|
|
void | printSolution (int l, int *s, int i, int j) |
| Recursively prints the solution.
|
|
static void | test () |
| Self-test implementations.
|
|
int | main () |
| Main function.
|
|
Matrix Chain Order
From Wikipedia: Matrix chain multiplication (or the matrix chain ordering problem) is an optimization problem concerning the most efficient way to multiply a given sequence of matrices. The problem is not actually to perform the multiplications, but merely to decide the sequence of the matrix multiplications involved.
- Author
- CascadingCascade
◆ main()
Main function.
- Returns
- 0
88 {
90 return 0;
91}
static void test()
Self-test implementations.
Definition: matrix_chain_order.c:70
◆ matrixChainOrder()
int matrixChainOrder |
( |
int |
l, |
|
|
const int * |
p, |
|
|
int * |
s |
|
) |
| |
for assert
for IO operations for INT_MAX macro for malloc() and free()
Finds the optimal sequence using the classic O(n^3) algorithm.
- Parameters
-
l | length of cost array |
p | costs of each matrix |
s | location to store results |
- Returns
- number of operations
24 {
25
26 int mat[l][l];
27 for (int i = 0; i < l; ++i) {
28 mat[i][i] = 0;
29 }
30
31 for (int cl = 1; cl < l; ++cl) {
32 for (int i = 0; i < l - cl; ++i) {
33 int j = i + cl;
34 mat[i][j] = INT_MAX;
35 for (int div = i; div < j; ++div) {
36 int q = mat[i][div] + mat[div + 1][j] + p[i] * p[div] * p[j];
37 if (q < mat[i][j]) {
38 mat[i][j] = q;
39 s[i * l + j] = div;
40 }
41 }
42 }
43 }
44 return mat[0][l - 1];
45}
◆ printSolution()
void printSolution |
( |
int |
l, |
|
|
int * |
s, |
|
|
int |
i, |
|
|
int |
j |
|
) |
| |
Recursively prints the solution.
- Parameters
-
l | dimension of the solutions array |
s | solutions |
i | starting index |
j | ending index |
- Returns
- void
55 {
56 if(i == j) {
57 printf("A%d",i);
58 return
59 }
60 putchar('(');
63 putchar(')');
64}
void printSolution(int l, int *s, int i, int j)
Recursively prints the solution.
Definition: matrix_chain_order.c:55
◆ test()
static void test |
( |
void |
| ) |
|
|
static |
Self-test implementations.
- Returns
- void
70 {
71 int sizes[] = {35,15,5,10,20,25};
72 int len = 6;
73 int *sol =
malloc(len * len *
sizeof(
int));
75 assert(r == 18625);
76 printf("Result : %d\n",r);
77 printf("Optimal ordering : ");
80
81 printf("\n");
82}
#define malloc(bytes)
This macro replace the standard malloc function with malloc_dbg.
Definition: malloc_dbg.h:18
#define free(ptr)
This macro replace the standard free function with free_dbg.
Definition: malloc_dbg.h:26
int matrixChainOrder(int l, const int *p, int *s)
for assert
Definition: matrix_chain_order.c:24