Sample EXP 3
Sample EXP 3
Experiment No. 4
MATRIX-CHAIN-MULTIPLICATION(p)
n = p.length ─ 1
let m[1…n, 1…n] and s[1…n ─ 1, 2…n] be new matrices
for i = 1 to n
m[i, i] = 0
for l = 2 to n // l is the chain length
for i = 1 to n - l + 1
j=i+l-1
m[i, j] = ∞
for k = i to j - 1
q = m[i, k] + m[k + 1, j] + pi-1pkpj
if q < m[i, j]
m[i, j] = q
s[i, j] = k
return m and s
Algorithm:
Matrix Chain Multiplication :
MATRIX-CHAIN-ORDER (p)
1. n length[p]-1
2. for i ← 1 to n
3. do m [i, i] ← 0
4. for l ← 2 to n // l is the chain length
5. do for i ← 1 to n-l + 1
6. do j ← i+ l -1
7. m[i,j] ← ∞
8. for k ← i to j-1
9. do q ← m [i, k] + m [k + 1, j] + pi-1 pk pj
10. If q < m [i,j]
11. then m [i,j] ← q
12. s [i,j] ← k
13. return m and s.
To print :
PRINT-OPTIMAL-PARENS (s, i, j)
1. if i=j
2. then print "A"
3. else print "("
4. PRINT-OPTIMAL-PARENS (s, i, s [i, j])
5. PRINT-OPTIMAL-PARENS (s, s [i, j] + 1, j)
6. print ")"
Program
Code : import java.util.Scanner;
class Dp {
static char name;
// 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] = Integer.MAX_VALUE;
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;
dp[i][j] = k;
}
}
}
}
System.out.println("\nOptimal Cost is : " + m[1][n - 1]);
Solving :
Result : 1. Best Case : O(n^3)
In the best case, the time complexity of the dynamic programming
approach for matrix chain multiplication is O(n^3), where n is the
number of matrices. This occurs when the input matrices are
already in the optimal order, and the algorithm only needs to fill
the dp table.
2. Average Case : O(n^3)
The average case time complexity of the dynamic programming
approach for matrix chain multiplication is also O(n^3). This is
because, on average, the algorithm will need to consider all
subproblems and fill the dp table, leading to cubic time complexity.
3. Worst Case : O(n^3)
The worst case time complexity of the dynamic programming
approach for matrix chain multiplication is O(n^3). This occurs
when the input matrices are in the worst possible order, and the
algorithm needs to consider all subproblems and fill the dp table,
resulting in the highest time complexity.