Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct Products{
- string name;
- int weight;
- int totalPrice;
- float unitPrice;
- float percentage;
- };
- void greedyKnapsack(Products p[], int n, int capacity)
- {
- int i,currentWeight=0;
- i=0;
- while (currentWeight<capacity)
- {
- if(currentWeight+p[i].weight<= capacity)
- {
- p[i].percentage = 100;
- currentWeight = currentWeight+p[i].weight;
- i++;
- }
- else
- {
- float temp = capacity - currentWeight;
- float temp2 = temp/p[i].weight;
- p[i].percentage = temp2 * 100;
- break;
- }
- }
- cout << "--------------------------------------------\n"<<endl;
- for(i=0; i<n; i++)
- {
- cout << p[i].name << " = ";
- cout << p[i].percentage << "%" <<endl;
- }
- float profit=0;
- for(i=0;i<n;i++)
- {
- if(p[i].percentage == 100)
- {
- profit = profit + p[i].totalPrice;
- }
- else
- {
- float temp1 = p[i].totalPrice * p[i].percentage;
- profit = profit + (temp1/100);
- }
- }
- cout << "\n-------------------------------------------\n"<<endl;
- cout << "Total profit: " << profit <<endl;
- }
- int main()
- {
- int i,j,capacity;
- cout << "Input Capacity: ";
- cin >> capacity;
- int type=0;
- cout << "Input Number of Types: ";
- cin >> type;
- Products p[type];
- for(i=0; i<type; i++)
- {
- cout << "Input product name: ";
- cin >> p[i].name;
- cout << "Input product weight: ";
- cin >> p[i].weight;
- cout << "Input product total price: ";
- cin >> p[i].totalPrice;
- p[i].unitPrice = p[i].totalPrice/p[i].weight;
- p[i].percentage = 0;
- }
- for(i=1;i<type;++i)
- {
- for(j=0;j<(type-i);++j)
- {
- if(p[j].unitPrice<p[j+1].unitPrice)
- {
- swap(p[j],p[j+1]);
- }
- }
- }
- greedyKnapsack(p,type,capacity);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment