DYNAMIC APPROACH ALGORITHM
#include<iostream.h>
#include<conio.h>
int i,j,k,n,r[10][10]={0},d,s,kmin;
float p[20],minval,sum,c[10][10];
class binary
{
public:
void getdata();
void calc();
void display();
};
void binary::getdata()
{
cout<<"\nEnter the total number key value:\n";
cin>>n;
cout<<"\nEnter probability value:\n";
for(i=1;i<=n;i++)
cin>>p[i];
}
void binary :: calc()
{
for(i=1;i<=n;i++)
{
c[i][i-1]=0;
c[i][i]=p[i];
r[i][i]=i;
}
c[n+1][n]=0;
for(d=1;d<=n-1;d++)
{
for(i=1;i<=n-d;i++)
{
j=i+d;
minval=1000;
for(k=i;k<=j;k++)
{
if(c[i][k-1]+c[k+1][j]<minval)
{
minval=c[i][k-1]+c[k+1][j];
kmin=k;
}
}
r[i][j]=kmin;
sum=p[i];
for(s=i+1;s<=j;s++)
c[i][j]=minval+sum;
}
}
}
void binary::display()
{
cout<<"\n\t\tMain Table\n\n\n";
cout<<"\t";
for(i=0;i<=n;i++)
cout<<"\t"<<i;
cout<<"\n";
for(i=1;i<=n+1;i++)
{
cout<<"\t"<<i;
for(j=0;j<=n;j++)
cout<<"\t"<<c[i][j];
cout<<"\n";
}
getch();
cout<<"\n\t\tRoot Table\n\n\n";
cout<<"\t";
for(i=0;i<=n;i++)
cout<<"\t"<<i;
cout<<"\n";
for(i=1;i<=n+1;i++)
{
cout<<"\t"<<i;
for(j=0;j<=n;j++)
cout<<"\t"<<r[i][j];
cout<<"\n";
}
}
void main()
{
clrscr();
binary bin;
bin.getdata();
bin.calc();
bin.display();
getch();
}
OUTPUT:
Enter the total number key value:
4
Enter probability value:
0.1
0.2
0.3
0.4
Main Table
0 1 2 3 4
1 0 0.1 0.4 1 1.8
2 0 0 0.2 0.7 1.5
3 0 0 0 0.3 1
4 0 0 0 0 0.4
5 0 0 0 0 0
Root Table
0 1 2 3 4
1 0 1 2 2 3
2 0 0 2 3 3
3 0 0 0 3 4
4 0 0 0 0 4
5 0 0 0 0 0
Comments
Post a Comment