-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfraction_knapsack.cpp
More file actions
78 lines (64 loc) · 1.34 KB
/
fraction_knapsack.cpp
File metadata and controls
78 lines (64 loc) · 1.34 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
/*
* Name :sharad Dixit
* Institute :IIIT -A
*/
#include <iostream>
using namespace std;
void sort ( int table[][100],int a)
{
for ( int i = 0; i < a; i++ ) {
for ( int j = 0 ; j < a-1; j++){
float k = table[j][1]/table[j][0];
float l = table[j+1][1]/table[j+1][0];
if (l > k){
int temp = table[j][1];
table[j][1] = table[j+1][1];
table[j+1][1] = temp;
temp = table[j][0];
table[j][0] = table[j+1][0];
table[j+1][0] = temp;
}
}
}
}
void knapsack(int b[][100],int a,int capacity){
int total = 0;
int price=0;
int i =0;
while ( total < capacity && i<a) {
total = total + b[i][0];
price = price + b[i][1];
i++;
}
i--;
price = price - b[i][1];
total = total - b[i][0];
int difference = capacity -total;
// cout << difference;
price = price + (difference)*b[i][1]/b[i][0];
cout << "OPTIMUM MONEY TAKEN - " << price;
}
int main()
{
int a;
int weight;
int cost;
int table[100][100];
int capacity;
cout << "NO. of items"<< endl;
cin >> a;
cout << "ENTER WEIGHT AND COST" << endl;
for ( int i =0; i<a; i++) {
cin >> weight>> cost;
table[i][0] = weight;
table[i][1]= cost;
}
cout << "CAPACITY OF KNAPSACK"<< endl;
cin >> capacity;
sort ( table,a);
/*
for ( int i = 0; i< a; i++) {
cout << table[i][0] << " " << table[i][1] << endl;
}*/
knapsack(table,a,capacity);
}