-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathknapf.cpp
More file actions
executable file
·73 lines (69 loc) · 1.16 KB
/
knapf.cpp
File metadata and controls
executable file
·73 lines (69 loc) · 1.16 KB
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
69
70
71
72
73
#include<iostream>
using namespace std;
class knapsack
{
float p,w;
float pw;
public:void create();
void sort();
void kp();
};
knapsack a[20],b[20];
int n,m;
void knapsack::create()
{
cout<<"Enter no. of objects\n";
cin>>n;
cout<<"Enter price,weight of object\n";
for(int i=0;i<n;i++)
cin>>a[i].p>>a[i].w;
for(int i=0;i<n;i++)
a[i].pw=(a[i].p/a[i].w);
cout<<"Enter the size of the bag\n";
cin>>m;
}
void knapsack::sort()
{
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(a[j].pw>a[j+1].pw)
{
knapsack temp;
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(int i=0;i<n;i++)
cout<<a[i].p<<" "<<a[i].w<<endl;
}
void knapsack::kp()
{
int rm=m;
float p=0;
for(int i=n-1;i>=0;i--)
{
if(rm>=a[i].w)
{ cout<<a[i].p<<" "<<a[i].w<<"if"<<endl;
p=p+a[i].p;
rm=rm-a[i].w;
}
else
{cout<<a[i].p<<" "<<a[i].w<<endl;
p=p+(a[i].pw*rm);
break;
}
}
cout<<"profit is"<<p;
}
int main()
{
knapsack ob;
ob.create();
ob.sort();
ob.kp();
return 0;
}