Loading…
DAA · Dynamic programming · Program 12 · In the record
Write a program in c to find the minimum number of scalar multiplications needed for matrix chain multiplication using dynamic programming and find its execution time using the time function.
Algorithm: MatrixChainOrder(p, n)
1. Start
2. For i <- 1 to n do
3. m[i][i] <- 0
4. For l <- 2 to n do
5. For i <- 1 to (n-l+1) do
6. j <- i+l-1
7. m[i][j] <- infinity
8. For k <- i to (j-1) do
9. q <- m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
10. if q < m[i][j] then
11. m[i][j] <- q
12. s[i][j] <- k
13. Print m[1][n] and PrintOrder(s, 1, n)
14. Stop
Algorithm: PrintOrder(s, i, j)
1. If (i == j) then
2. print "A"i
3. else
4. print "("
5. PrintOrder(s, i, s[i][j])
6. PrintOrder(s, s[i][j]+1, j)
7. print ")"1#include<stdio.h>2#include<time.h>3 4int s[20][20];5 6void printOrder(int i,int j) {7 if(i==j) {8 printf("A%d",i);9 return;10 }11 printf("(");12 printOrder(i,s[i][j]);13 printOrder(s[i][j]+1,j);14 printf(")");15}16 17int main() {18 int n,i,j,k,l,count=0;19 printf("Enter the number of matrices:");20 scanf("%d",&n);21 int p[n+1];22 printf("Enter the %d dimensions (matrix i is p[i-1] x p[i]):",n+1);23 for(i=0;i<=n;i++)24 scanf("%d",&p[i]);25 int m[20][20];26 27 clock_t start=clock();28 for(i=1;i<=n;i++)29 m[i][i]=0;30 for(l=2;l<=n;l++) {31 for(i=1;i<=n-l+1;i++) {32 j=i+l-1;33 m[i][j]=999999999;34 for(k=i;k<j;k++) {35 count++;36 int cost=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];37 if(cost<m[i][j]) {38 m[i][j]=cost;39 s[i][j]=k;40 }41 }42 }43 }44 clock_t end=clock();45 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;46 47 printf("\nCost table:");48 for(i=1;i<=n;i++) {49 printf("\n");50 for(j=1;j<=n;j++)51 if(j<i)52 printf("\t-");53 else54 printf("\t%d",m[i][j]);55 }56 printf("\nMinimum number of multiplications:%d",m[1][n]);57 printf("\nOptimal parenthesization:");58 printOrder(1,n);59 printf("\nNumber of comparisons:%d",count);60 printf("\nTime taken:%f seconds",time_taken);61 printf("\nTime complexity: O(n^3)");62 printf("\nSpace complexity: O(n^2)");63 printf("\n");64 return 0;65}4 ⏎ 5 4 6 2 7Enter the number of matrices:4 Enter the 5 dimensions (matrix i is p[i-1] x p[i]):5 4 6 2 7 Cost table: 0 120 88 158 - 0 48 104 - - 0 84 - - - 0 Minimum number of multiplications:158 Optimal parenthesization:((A1(A2A3))A4) Number of comparisons:10 Time taken:0.000004 seconds Time complexity: O(n^3) Space complexity: O(n^2)
Run program 12 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.