编辑代码

#include <stdio.h>

#define NUM_FRUITS 4
#define MAX_WEIGHT 20

typedef struct {
    char name[20];
    int weight;
    int value;
} Fruit;

void printKnapsack(Fruit fruits[], int dp[][MAX_WEIGHT + 1], int winner);

int max(int a, int b) {
    return (a > b) ? a : b;
}

void knapsack(Fruit fruits[], int winner) {
    int dp[NUM_FRUITS + 1][MAX_WEIGHT + 1];

    for (int i = 0; i <= NUM_FRUITS; i++) {
        for (int w = 0; w <= MAX_WEIGHT; w++) {
            if (i == 0 || w == 0) {
                dp[i][w] = 0;
            } else if (fruits[i - 1].weight <= w) {
                dp[i][w] = max(dp[i - 1][w], fruits[i - 1].value + dp[i - 1][w - fruits[i - 1].weight]);
            } else {
                dp[i][w] = dp[i - 1][w];
            }
        }
    }

    printKnapsack(fruits, dp, winner);
}

void printKnapsack(Fruit fruits[], int dp[][MAX_WEIGHT + 1], int winner) {
    printf("最大价值的装备策略为:\n");

    int i = NUM_FRUITS;
    int w = MAX_WEIGHT;

    while (i > 0 && w > 0) {
        if (dp[i][w] != dp[i - 1][w]) {
            printf("%s\n", fruits[i - 1].name);
            w -= fruits[i - 1].weight;
        }
        i--;
    }

    printf("总重量:%d kg\n", MAX_WEIGHT - w);
    printf("总价值:%d 元\n", dp[NUM_FRUITS][MAX_WEIGHT]);

}

int main() {
    Fruit fruits[NUM_FRUITS] = {
        {"苹果", 15, 300},
        {"香蕉", 18, 180},
        {"橘子", 10, 150},
        {"猕猴桃", 9, 270}
    };

    // 假设三个参赛者的编号分别为1、2、3
    int winner = 0;
    int max_value = 0;

    for (int i = 1; i <= 3; i++) {
        printf("计算参赛者 %d 的装备策略:\n", i);
        knapsack(fruits, i);
        printf("\n");

        // 记录最大价值和获胜者
        if (fruits[NUM_FRUITS].value > max_value) {
            max_value = fruits[NUM_FRUITS].value;
            winner = i;
        }
    }

    return 0;
}