#include <stdio.h>
#include <iostream>
using namespace std;
struct item{
char name[20];
int rest;
float price;
};
void greedyBackpack(struct item product[], int length, int capacity){
struct item temp;
float total = 0;
for(int i = 0; i < length; i++){
product[i].price = product[i].price / product[i].rest;
}
for(int i = 0; i < length; i++){
for(int j = i + 1; j < length; j++){
if(product[i].price < product[j].price){
temp = product[i];
product[i] = product[j];
product[j] = temp;
}
}
}
cout << "当背包的承重为" << capacity << "kg时,能装入最高价值的水果为:" << endl;
for(int i = 0; i < length; i++){
if(capacity >= product[i].rest){
capacity = capacity - product[i].rest;
total += product[i].rest * product[i].price;
cout << product[i].rest << "kg" << product[i].name << endl;
}else if(capacity < product[i].rest){
total += capacity *product[i].price;
cout << capacity << "kg" << product[i].name << endl;
break;
}
}
cout << "总价值为:" << total << "元" << endl;
}
int main () {
struct item product[] = {{"苹果", 15, 300}, {"香蕉", 18, 180}, {"橘子", 10, 150}, {"猕猴桃", 9, 270}};
int length = sizeof(product) / sizeof(product[0]);
int capacity = 20;
greedyBackpack(product, length, capacity);
return 0;
}