#include <stdio.h>
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;
}
}
}
printf("%dkg背包时\n最多拿取", capacity);
for(int i = 0; i < length; i++){
if(capacity >= product[i].rest){
capacity = capacity - product[i].rest;
total += product[i].rest * product[i].price;
printf("%dkg%s ", product[i].rest, product[i].name);
}else if(capacity < product[i].rest){
total += capacity *product[i].price;
printf("%dkg%s", capacity, product[i].name);
break;
}
}
printf("\n总价值为%.2f元", total);
}
int main () {
struct item product[] = {{"黄豆", 100, 100}, {"绿豆", 30, 90}, {"红豆", 60, 120}, {"黑豆", 20, 80}, {"青豆", 50, 75}};
int length = sizeof(product) / sizeof(product[0]);
int capacity = 100;
greedyBackpack(product, length, capacity);
return 0;
}