TheAlgorithms-C-Plus-Plus/greedy_algorithms/Knapsack.cpp

93 lines
1.7 KiB
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2017-02-20 11:38:44 +08:00
using namespace std;
struct Item
{
int weight;
int profit;
};
2017-02-20 11:56:23 +08:00
float profitPerUnit(Item x)
2017-02-20 11:38:44 +08:00
{
2019-08-21 10:10:08 +08:00
return (float)x.profit / (float)x.weight;
2017-02-20 11:56:23 +08:00
}
2019-08-21 10:10:08 +08:00
int partition(Item arr[], int low, int high)
2017-02-20 11:56:23 +08:00
{
2019-08-21 10:10:08 +08:00
Item pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j < high; j++)
{
// If current element is smaller than or
// equal to pivot
if (profitPerUnit(arr[j]) <= profitPerUnit(pivot))
{
i++; // increment index of smaller element
Item temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Item temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
2017-02-20 11:56:23 +08:00
}
2017-02-20 12:51:01 +08:00
void quickSort(Item arr[], int low, int high)
2017-02-20 11:56:23 +08:00
{
2019-08-21 10:10:08 +08:00
if (low < high)
{
2017-02-20 11:56:23 +08:00
2019-08-21 10:10:08 +08:00
int p = partition(arr, low, high);
2017-02-20 11:56:23 +08:00
2019-08-21 10:10:08 +08:00
quickSort(arr, low, p - 1);
quickSort(arr, p + 1, high);
}
}
2017-02-20 12:51:01 +08:00
2017-02-20 11:56:23 +08:00
int main()
{
2019-08-21 10:10:08 +08:00
cout << "\nEnter the capacity of the knapsack : ";
2017-02-20 12:51:01 +08:00
float capacity;
2019-08-21 10:10:08 +08:00
cin >> capacity;
cout << "\n Enter the number of Items : ";
2017-02-20 11:56:23 +08:00
int n;
2019-08-21 10:10:08 +08:00
cin >> n;
2017-02-20 12:51:01 +08:00
Item itemArray[n];
2017-02-20 11:56:23 +08:00
for (int i = 0; i < n; i++)
{
2019-08-21 10:10:08 +08:00
cout << "\nEnter the weight and profit of item " << i + 1 << " : ";
cin >> itemArray[i].weight;
cin >> itemArray[i].profit;
2017-02-20 11:56:23 +08:00
}
2019-08-21 10:10:08 +08:00
quickSort(itemArray, 0, n - 1);
2017-02-20 12:51:01 +08:00
// show(itemArray, n);
2017-02-20 11:56:23 +08:00
2019-08-21 10:10:08 +08:00
float maxProfit = 0;
int i = n;
while (capacity > 0 && --i >= 0)
2017-02-20 11:56:23 +08:00
{
2019-08-21 10:10:08 +08:00
if (capacity >= itemArray[i].weight)
2017-02-20 11:56:23 +08:00
{
2019-08-21 10:10:08 +08:00
maxProfit += itemArray[i].profit;
capacity -= itemArray[i].weight;
cout << "\n\t" << itemArray[i].weight << "\t" << itemArray[i].profit;
2017-02-20 11:56:23 +08:00
}
else
{
2019-08-21 10:10:08 +08:00
maxProfit += profitPerUnit(itemArray[i]) * capacity;
cout << "\n\t" << capacity << "\t" << profitPerUnit(itemArray[i]) * capacity;
capacity = 0;
2017-02-20 11:56:23 +08:00
break;
}
}
2019-08-21 10:10:08 +08:00
cout << "\nMax Profit : " << maxProfit;
2017-02-20 11:56:23 +08:00
2017-02-20 11:38:44 +08:00
return 0;
2017-02-20 12:51:01 +08:00
}