0% found this document useful (0 votes)
4 views3 pages

Assignment-4 DAA Kawaljeet Singh

This document is an assignment for the Design and Analysis of Algorithms course, authored by Kawaljeet Singh. It includes a C++ implementation of the matrix chain order algorithm, which calculates the minimum number of multiplications needed to multiply a chain of matrices and prints the optimal parenthesization. The source code is provided along with instructions for user input.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Assignment-4 DAA Kawaljeet Singh

This document is an assignment for the Design and Analysis of Algorithms course, authored by Kawaljeet Singh. It includes a C++ implementation of the matrix chain order algorithm, which calculates the minimum number of multiplications needed to multiply a chain of matrices and prints the optimal parenthesization. The source code is provided along with instructions for user input.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Assignment-4

Subject: Design and Analysis of Algorithms(ICT 206)


Name: Kawaljeet Singh
Roll no: 06016401523

1. Implement matrix chain order, print optimal parameters, recursive and memoised
matrix chains.

Source Code:
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

void printOptimalParens(vector<vector<int>>& s, int i, int j) {


if (i == j)
cout << "A" << i;
else {
cout << "(";
printOptimalParens(s, i, s[i][j]);
printOptimalParens(s, s[i][j] + 1, j);
cout << ")";
}
}
void matrixChainOrder(int p[], int n) {
vector<vector<int>> m(n, vector<int>(n, 0));
vector<vector<int>> s(n, vector<int>(n, 0));
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; k++) {
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;
s[i][j] = k;
}
}
}
}
cout << "Minimum number of multiplications: " << m[1][n-1] << endl;
cout << "Optimal Parenthesization: ";
printOptimalParens(s, 1, n-1);
cout << endl;
}

int main() {
int n;
cout << "Enter the number of matrices: ";
cin >> n;
int p[n+1];

cout << "Enter the dimensions array: ";


for (int i = 0; i <= n; i++)
cin >> p[i];

matrixChainOrder(p, n+1);
return 0;
}

Output:​

You might also like