-
Notifications
You must be signed in to change notification settings - Fork 0
/
KnapSack.CPP
68 lines (59 loc) · 1.02 KB
/
KnapSack.CPP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<iostream.h>
#include<conio.h>
float w[10],p[10],pwd[10],n,c,x[10];
int index[10];
void sort()
{
for(int i=0;i<n;i++)
index[i]=i;
for(i=1;i<n;i++)
for(int j=0;j<n-i;j++)
if(pwd[j]<=pwd[j+1])
{
float temp=pwd[j];
pwd[j]=pwd[j+1];
pwd[j+1]=temp;
int tempi=index[j];
index[j]=index[j+1];
index[j+1]=tempi;
}
}
void load()
{
sort();
int c1=0;
for(int i=0;i<n;i++)
{
c1=c1+w[index[i]];
x[index[i]]=1;
if(c1>c)
{
x[index[i]]=0;
c1-=w[index[i]];
}
}
cout<<"solution:"<<endl;
float profit=0;
for( i=0;i<n;i++)
{
if(x[i]!=0)
profit+=p[i];
cout<<" "<<x[i];
}
cout<<endl<<"Profit="<<profit<<endl;
}
void main()
{
clrscr();
cout<<"enter no of articles"<<endl;
cin>>n;
cout<<"enter capacity"<<endl;
cin>>c;
cout<<"enter weights snd profits"<<endl;
for(int i=0;i<n;i++)
cin>>w[i]>>p[i];
for(i=0;i<n;i++)
pwd[i]=p[i]/w[i];
load ();
getch();
}