WAP to implement the Knapsack Proble

Document Sample
WAP to implement the Knapsack Proble Powered By Docstoc
					                             PROGRAM NO. - 10

Aim:-WAP to implement the Knapsack Problem.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>

void main()
{
 clrscr();
 int c[10],v[10];
 int cur_w,n,W;
 float tot_v;
 int i, maxi;
 int used[10];

cout<<"Enter the no. of items:";
cin>>n;
cout<<"Enter the values and weights :\n";
for(i=1;i<=n;i++)
 {
  cout<<"\nEnter the data for "<<i;
  cout<<"\nEnter the weight: ";
  cin>>c[i];
  cout<<"Enter the value: ";
  cin>>v[i];
 }
 cout<<"\nEnter the maximum capacity:";
 cin>>W;

 for(i=1;i<=n;++i)
  used[i] = 0;

 cur_w = W;
 while(cur_w > 0)
  {
    maxi = -1;
    for(i=1;i<=n; ++i)
    if ((used[i]==0)&&((maxi==-1)||((float)v[i]/c[i]>(float)v[maxi]/c[maxi])))
         maxi = i;

    used[maxi] = 1;
    cur_w -= c[maxi];
    tot_v += v[maxi];
    if(cur_w >= 0)
        cout<<"Added object "<<maxi<<" ("<< v[maxi]<<" , "<<c[maxi]<<") completly in
the bag.Space Left:" <<cur_w<<".\n";
    else
        {
          cout<<"Added "<<(int)((1 + (float)cur_w/c[maxi]) * 100)<<"%%
("<<v[maxi]<<","<<c[maxi]<<" ) of object "<<maxi<<" in the bag.\n";
          tot_v -= v[maxi];
          tot_v += (1 + (float)cur_w/c[maxi]) * v[maxi];
        }
  }

  cout<<"Filled the bag with objects worth "<< tot_v<<".\n";
 getch();
}
                                      OUTPUT

Enter the no. of items:4
Enter the values and weights :

Enter the data for 1
Enter the weight: 50
Enter the value: 10

Enter the data for 2
Enter the weight: 40
Enter the value: 4

Enter the data for 3
Enter the weight: 10
Enter the value: 5

Enter the data for 4
Enter the weight: 20
Enter the value: 10

Enter the maximum capacity:50
Added object 3 (5, 10) completly in the bag. Space Left: 40.
Added object 4 (10, 20) completly in the bag. Space Left: 20.
Added 39% (10, 50) of object 1 in the bag.
Filled the bag with objects worth 19.

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:41
posted:4/30/2012
language:
pages:3
Description: This document contain Design and Algorithm Analysis Lab practicals for CSE students under Kurukshetra University scheme.