编辑代码

#include <stdio.h>
// 定义物品结构体
typedef struct {
    int weight;
    int value;
} Item;

int max(int a, int b) {
    return a > b ? a : b;
}
// 装水果策略
void fruit(Item items[], int n, int capacity) {
    // 创建动态规划表格
    int dp[n+1][capacity+1];
    // 填充动态规划表格
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= capacity; j++) {
            if (i == 0 || j == 0)
                dp[i][j] = 0;
            else if (items[i-1].weight <= j)
                dp[i][j] = max(items[i-1].value + dp[i-1][j-items[i-1].weight], dp[i-1][j]);
            else
                dp[i][j] = dp[i-1][j];
        }
    }
    // 打印装水果的策略
    int i = n, j = capacity;
    while (i > 0 && j > 0) {
        if (dp[i][j] != dp[i-1][j]) {
            printf("选择装入物品: %d\n", i);
            i--;
            j -= items[i].weight;
        }
        else {
            i--;
        }
    }
}

int main() {
    // 初始化物品数组
    Item items[] = {
        {15, 300},
        {18, 180},
        {10, 150},
        {9, 270}
    };
    int n = sizeof(items) / sizeof(items[0]);
    int capacity = 20;
    fruit(items, n, capacity);
    
    return 0;
}