编辑代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char name[20];
    double totalWeight;
    double totalValue;
} GreedyItem;

int compare(const void* left, const void* right) {
    GreedyItem* leftItem = (GreedyItem*)left;
    GreedyItem* rightItem = (GreedyItem*)right;
    
    double leftUnitPrice = leftItem->totalValue / leftItem->totalWeight;
    double rightUnitPrice = rightItem->totalValue / rightItem->totalWeight;
    
    if (leftUnitPrice > rightUnitPrice) {
        return -1;
    }
    else if (leftUnitPrice == rightUnitPrice) {
        return 0;
    }
    else {
        return 1;
    }
}

void packBean(int packCapacity, GreedyItem* items, int itemCount, GreedyItem* beans, int* beanCount) {
    qsort(items, itemCount, sizeof(GreedyItem), compare);
    
    int leftPackCapacity = packCapacity;
    *beanCount = 0;
    
    for (int i = 0; i < itemCount; ++i) {
        if (leftPackCapacity > items[i].totalWeight) {
            leftPackCapacity -= items[i].totalWeight;
            beans[*beanCount] = items[i];
            (*beanCount)++;
        }
        else {
            double unitPrice = items[i].totalValue / items[i].totalWeight;
            double packWeight = leftPackCapacity;
            double packValue = packWeight * unitPrice;
            
            strcpy(beans[*beanCount].name, items[i].name);
            beans[*beanCount].totalWeight = packWeight;
            beans[*beanCount].totalValue = packValue;
            
            (*beanCount)++;
            leftPackCapacity = 0;
            break;
        }
    }
}

void test() {
    GreedyItem items[] = {
        {"黄豆", 100, 100},
        {"绿豆", 30, 90},
        {"红豆", 60, 120},
        {"黑豆", 20, 80},
        {"青豆", 50, 75}
    };
    int itemCount = sizeof(items) / sizeof(GreedyItem);

    GreedyItem beans[itemCount];
    int beanCount = 0;

    int packCapacity = 100;
    
    packBean(packCapacity, items, itemCount, beans, &beanCount);

    double maxValue = 0;

    printf("装了如下物品:\n");
    for (int i = 0; i < beanCount; ++i) {
        maxValue += beans[i].totalValue;
        printf("%s %.2f\n", beans[i].name, beans[i].totalWeight);
    }

    printf("总价值:%.2f\n", maxValue);
}

int main() {
    test();
    return 0;
}