#include<iostream>
using namespace std;
class obst
{
int p[10],q[10]; // p -> probability of success : q -> probability of failure
int arr[10]; // array of elements
int weight[10][10],root[10][10],cost[10][10]; // resultant for obst i.e.,weight , root , cost
int n; // n -> no. of elements
public:
void get()
{
cout<<"ENTER NUMBER OF ELEMENTS = ";
cin>>n;
cout<<": INPUT DATA ( ELEMENT , PROBABILITIES ) :"<<endl;
for( int i = 1 ; i <= n ; i++ )
{
cout<<"ELEMENT "<<i<<" = "; //element
cin>>arr[i];
cout<<"p ["<<i<<"] = "; //success probability
cin>>p[i];
cout<<"q ["<<i-1<<"] = "; //failure probability
cin>>q[i-1];
}
cout<<"q ["<<n<<"] = "; // last failure probability
cin>>q[n];
}
void constobst()
{
get();
int k = 0,j = 0; //a variable which stores the index of minimum cost
//Initialize the values of weight, cost and root
for( int i = 0 ; i <= n ; i++)
{
weight[i][i] = q[i]; // as according to formula ,i.e., ( w[i][j] = q[i] + p[k] + q[k] )
// where, i < k < j ; so as no value of k when i = j therefore (w[i][i] = q[i] + 0)
cost[i][i] = root[i][i] = 0; // initial cost and root is 0
}
// m is the difference of j and i
for( int m = 1 ; m <= n ; m++)
{
for(int i = 0 ; i < n ; i++)
{
j = i + m;
weight[i][j] = weight[i][j-1] + p[j] + q[j]; // weight of all elements
k = kmin(i,j); // call to kmin function which returns the index value of k by which we get minimum cost
cost[i][j] = cost[i][k-1] + cost[k][j] + weight[i][j];
root[i][j] = k;
}
}
cout<<"ROOT NODE : "<<arr[root[0][n]];
cout<<endl<<"LEFT NODE of "<<arr[root[0][n]]<<" : ";
obtree( 0 , root[0][n] -1 );
cout<<endl<<"RIGHT NODE of "<<arr[root[0][n]]<<" : ";
obtree(root[0][n] , n );
}
int kmin(int i , int j)
{
int min = 999 , z = 0;
// if j - i = 1 then only possible value of k is j : as i < k <= j
if( j - i == 1)
{
return j;
}
else
{
// i < k <= j ; and we need to minimise the value of (cost[i][k-1] + cost[k][j])
for(int k = i+1 ; k <= j ; k++)
{
if(min > (cost[i][k-1] + cost[k][j]))
{
z = k;
min = (cost[i][k-1] + cost[k][j]);
}
}
}
return z;
}
void obtree(int i , int j)
{
if(root[i][j] == 0)
{
cout<<"NULL"<<endl;
return;
}
cout<<arr[root[i][j]]<<endl;
cout<<endl<<"LEFT NODE OF "<<arr[root[i][j]]<<" : ";
obtree( i , root[i][j] -1 );
cout<<endl<<"RIGHT NODE OF "<<arr[root[i][j]]<<" : ";
obtree(root[i][j] , j );
}
};
int main()
{
obst o;
o.constobst();
return 0;
}
Comments
Post a Comment