Dynamic Programming: Optimal Matrix Chain Multipli- cation Order In this assignm
ID: 3601298 • Letter: D
Question
Dynamic Programming: Optimal Matrix Chain Multipli- cation Order In this assignment you are asked to implement a dynamic programming algorithm: matrix chain multiplication (chapter 15.2), where the goal is to find the most computationally efficient matrix order when multiplying an arbitrary number of matrices in a row. You can assume that the that matrix sizes will be at least 1. You will use "Grade06" to grade your code. Your execution file name must be "MatrixChain.exe". Refer to the previous lab assignments for instructions on how to use the grading tool. The input has the following format. The first number, n 1, in the test case will tell you how many matrices are in the sequence. The first number will be then followed by n1 numbers indicating the size of the dimensions of the matrices. Recall that the given information is enough to fully specify the dimensions of the matrices to be multiplied. First, you need to output the minimu number of scalar multiplications needed to multiply the given matrices. Then, print the matrix multiplication sequence, via parentheses, that minimizes the total number of multiplications. Each matrix should be named A, where # is the matrix number starting at 0 (zero) and ending at n - 1. See the examples belowExplanation / Answer
#include<bits/stdc++.h>
using namespace std;
void printParenthesis(int i, int j, int n,
int *bracket, char &name)
{
if (i == j)
{
cout << name++;
return;
}
cout << "(";
printParenthesis(i, *((bracket+i*n)+j), n,
bracket, name);
printParenthesis(*((bracket+i*n)+j) + 1, j,
n, bracket, name);
cout << ")";
}
void matrixChainOrder(int p[], int n)
{
int m[n][n];
int bracket[n][n];
for (int i=1; i<n; i++)
m[i][i] = 0;
// L is chain length.
for (int L=2; L<n; L++)
{
for (int i=1; i<n-L+1; i++)
{
int j = i+L-1;
m[i][j] = INT_MAX;
for (int k=i; k<=j-1; k++)
{
// q = cost/scalar multiplications
int q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
{
m[i][j] = q;
bracket[i][j] = k;
}
}
}
}
char name = 'A';
cout <<m[1][n-1]<<endl;
printParenthesis(1, n-1, n, (int *)bracket, name);
}
// Driver code
int main()
{
cout<<"please enter input"<<endl;
int n;
cin>>n;
int arr[n+1];
int x;
for (int i=0;i<=n;i++){
cin>>x;
arr[i]=x;
}
// int arr[] = {40, 20, 30, 10, 30};
int size = sizeof(arr)/sizeof(arr[0]);
matrixChainOrder(arr, size);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.