TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
knapsack.cpp
1#include <iostream>
2using namespace std;
3
4struct Item {
5 int weight;
6 int profit;
7};
8
9float profitPerUnit(Item x) { return (float)x.profit / (float)x.weight; }
10
11int partition(Item arr[], int low, int high) {
12 Item pivot = arr[high]; // pivot
13 int i = (low - 1); // Index of smaller element
14
15 for (int j = low; j < high; j++) {
16 // If current element is smaller than or
17 // equal to pivot
18 if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) {
19 i++; // increment index of smaller element
20 Item temp = arr[i];
21 arr[i] = arr[j];
22 arr[j] = temp;
23 }
24 }
25 Item temp = arr[i + 1];
26 arr[i + 1] = arr[high];
27 arr[high] = temp;
28 return (i + 1);
29}
30
31void quickSort(Item arr[], int low, int high) {
32 if (low < high) {
33 int p = partition(arr, low, high);
34
35 quickSort(arr, low, p - 1);
36 quickSort(arr, p + 1, high);
37 }
38}
39
40int main() {
41 cout << "\nEnter the capacity of the knapsack : ";
42 float capacity;
43 cin >> capacity;
44 cout << "\n Enter the number of Items : ";
45 int n;
46 cin >> n;
47 Item *itemArray = new Item[n];
48 for (int i = 0; i < n; i++) {
49 cout << "\nEnter the weight and profit of item " << i + 1 << " : ";
50 cin >> itemArray[i].weight;
51 cin >> itemArray[i].profit;
52 }
53
54 quickSort(itemArray, 0, n - 1);
55
56 // show(itemArray, n);
57
58 float maxProfit = 0;
59 int i = n;
60 while (capacity > 0 && --i >= 0) {
61 if (capacity >= itemArray[i].weight) {
62 maxProfit += itemArray[i].profit;
63 capacity -= itemArray[i].weight;
64 cout << "\n\t" << itemArray[i].weight << "\t"
65 << itemArray[i].profit;
66 } else {
67 maxProfit += profitPerUnit(itemArray[i]) * capacity;
68 cout << "\n\t" << capacity << "\t"
69 << profitPerUnit(itemArray[i]) * capacity;
70 capacity = 0;
71 break;
72 }
73 }
74
75 cout << "\nMax Profit : " << maxProfit;
76 delete[] itemArray;
77 return 0;
78}
int main()
Main function.