-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack.cpp
More file actions
117 lines (97 loc) · 2.07 KB
/
Knapsack.cpp
File metadata and controls
117 lines (97 loc) · 2.07 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include<bits/stdc++.h>
using namespace std;
#define size 100
void greedy_knapsack(int m, int n, double p[], double w[], double x[])
{
for(int i = 1; i < n; i++)
{
int maximum = i;
for(int j = i+1; j <= n; j++)
{
//if(p[j]>p[maximum]) /// only use for unit price
if(p[j]/w[j] > p[maximum]/w[maximum])
{
maximum = j;
}
}
swap(p[maximum],p[i]);
swap(w[maximum],w[i]);
}
for(int i = 1; i <= n; i++)
{
x[i] = 0.0;
}
int U = m,i;
for( i = 1; i <= n; i++)
{
if(w[i]>U)
{
break;
}
x[i] = 1;
U = U - w[i];
}
if(i <= n)
{
x[i] = (U/w[i]);
}
}
void profit_calculation(int n,double p[],double x[])
{
double sum = 0;
for(int i = 1; i <= n; i++)
{
sum += x[i] * p[i];
}
cout<<endl<<sum;
}
int main()
{
freopen("in.txt","r",stdin);
double p[size], w[size],x[size];
int u,n;
cin>>u>>n; //u = total capacity n = total element
// For taking input profit and weight
for(int i = 1; i<=n; i++)
{
cin>>p[i];
}
for(int i = 1; i<=n; i++)
{
cin>>w[i];
}
cout<<endl;
// To show entered profit
for(int i = 1; i<=n; i++)
{
cout<<p[i]<<" ";
}
cout<<endl;
// To show entered weight
for(int i = 1; i<=n; i++)
{
cout<<w[i]<<" ";
}
cout<<endl;
greedy_knapsack(u,n,p,w,x);
cout<<"After Sorting the Weight and Profit according with Unit :"<<endl;
for(int i = 1; i <= n;i++)
{
cout<<p[i]<<" ";
}
cout<<endl;
for(int i = 1; i <= n;i++)
{
cout<<w[i]<<" ";
}
cout<<endl;
cout<<"Portion of each Item : "<<endl;
for(int i = 1; i <= n;i++)
{
cout<<x[i]<<" ";
}
cout<<endl;
cout<<"Your Total Profit is : ";
profit_calculation(n,p,x);
return 0;
}