0% found this document useful (0 votes)
5 views2 pages

13

The document contains code for solving two problems - matrix chain multiplication and optimal binary search tree. The matrix chain multiplication algorithm takes an array of dimensions and returns the minimum number of multiplications. The optimal binary search tree algorithm takes an array of keys and frequencies and returns the cost of the optimal binary search tree.

Uploaded by

PARTH VYAVHARE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

13

The document contains code for solving two problems - matrix chain multiplication and optimal binary search tree. The matrix chain multiplication algorithm takes an array of dimensions and returns the minimum number of multiplications. The optimal binary search tree algorithm takes an array of keys and frequencies and returns the cost of the optimal binary search tree.

Uploaded by

PARTH VYAVHARE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

//slip-13

q1]

#include<stdio.h>
#include<limits.h>
int MatrixChainOrder(int p[],int i,int j)
{
if(i ==j)
return 0;
int k;
int min=INT_MAX;
int count;

for(k=i;k<j;k++)
{
count=MatrixChainOrder(p,i,k) +MatrixChainOrder(p,k+1,j) +p[i-1] *p[k]
*p[j];

if(count <min)
min=count;
}
return min;
}
int main()
{
int i,n;
/*int arr[10];

printf("Enter the number of matrix:");


scanf("%d",&n);

printf("Enter the dimensions of the matrix:");


for(i=0;i<=n;i++)
{
scanf("%d",&arr[i]);
}
*/
int arr[]={1,50,20,30,15};
int N=sizeof(arr)/sizeof(arr[0]);
printf(" Minimum number of multiplication is %d ",MatrixChainOrder(arr,1,N-1));

return 0;
}
_____________________________________________________
q2]

#include <stdio.h>
#include <limits.h>

int sum(int freq[], int i, int j);

int optCost(int freq[], int i, int j)


{

if (j < i)
return 0;
if (j == i)
return freq[i];
int fsum = sum(freq, i, j);

int min = INT_MAX;

for (int r = i; r <= j; ++r)


{
int cost = optCost(freq, i, r-1) +
optCost(freq, r+1, j);
if (cost < min)
min = cost;
}

return min + fsum;


}

int optimalSearchTree(int keys[], int freq[], int n)


{

return optCost(freq, 0, n-1);


}

int sum(int freq[], int i, int j)


{
int s = 0;
for (int k = i; k <=j; k++)
s += freq[k];
return s;
}

int main()
{
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = sizeof(keys)/sizeof(keys[0]);
printf("Cost of Optimal BST is %d ",
optimalSearchTree(keys, freq, n));
return 0;
}

You might also like