-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathknapsackFructional.cpp
More file actions
110 lines (88 loc) · 1.89 KB
/
knapsackFructional.cpp
File metadata and controls
110 lines (88 loc) · 1.89 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
#include<bits/stdc++.h>
using namespace std;
void k(int n,int cap,int *weight,int *profit,float *rat)
{
float tp=0,rc=cap;
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n; j++)
{
if(rat[i]<rat[j])
{
swap(rat[j],rat[i]);
swap(weight[j],weight[i]);
swap(profit[j],profit[i]);
}
}
}
int i;
for(i=0; i<n; i++)
{
if(weight[i]>rc)
{
tp+=(rc/weight[i])*profit[i];
break;
}
else
{
tp+=profit[i];
rc-=weight[i];
}
}
cout<<tp;
}
int main()
{
int n,capacity;
cin>>n>>capacity;
int weight[n],profit[n];
float rat[n];
for(int i=0; i<n; i++) cin>>weight[i];
for(int i=0; i<n; i++) cin>>profit[i];
for(int i=0; i<n; i++) rat[i]=profit[i]*1.0/weight[i];
for(int i=0;i<n;i++) cout<<rat[i]<<" ";
cout<<endl;
k(n,capacity,weight,profit,rat);
}
/*
#include <bits/stdc++.h>
using namespace std;
struct Item{
int value;
int weight;
};
bool cmp(Item a, Item b)
{
return a.value/(a.weight*1.0)>b.value/(b.weight*1.0);
}
//Function to get the maximum total value in the knapsack.
double fractionalKnapsack(int W, Item arr[], int n)
{
// Your code here
sort(arr,arr+n,cmp);
double res=0.00;
for(int i=0;i<n;i++){
auto x=arr[i];
if(x.weight<=W){
W-=x.weight;
res+=x.value;
}
else{
res+=W*x.value/(1.0*x.weight);
break;
}
}
return res;
}
int main()
{
int n,w;
cin>>n>>w;
Item arr[n];
//value and weight of each item
for(int i=0;i<n;i++){
cin>>arr[i].value>>arr[i].weight;
}
cout<<fractionalKnapsack(w,arr, n)<<endl;
}
*/