编辑代码

#include <iostream>
#include <algorithm>

void knapsack(int weight[], int value[], int n, int totalWeight) {
    int dp[n + 1][totalWeight + 1];

    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= totalWeight; j++) {
            if (i == 0 || j == 0) {
                dp[i][j] = 0;
            } else if (j >= weight[i - 1]) {
                dp[i][j] = std::max(dp[i - 1][j], dp[i - 1][j - weight[i - 1]] + value[i - 1]);
            } else {
                dp[i][j] = dp[i - 1][j];
            }
        }
    }

    int maxValue = dp[n][totalWeight];
    std::cout << "最大总价值为:" << maxValue << std::endl;

    // 输出选择的水果
    std::cout << "选择的水果有:" << std::endl;
    int remainingWeight = totalWeight;
    for (int i = n; i > 0 && maxValue > 0; i--) {
        if (maxValue != dp[i - 1][remainingWeight]) {
            std::cout << "水果" << i << "(重量:" << weight[i - 1] << "kg,价值:" << value[i - 1] << "元)" << std::endl;
            maxValue -= value[i - 1];
            remainingWeight -= weight[i - 1];
        }
    }
}

int main() {
    int weight[] = {15, 18, 10, 9};
    int value[] = {300, 180, 150, 270};
    int totalWeight = 20;
    int n = sizeof(weight) / sizeof(weight[0]);

    knapsack(weight, value, n, totalWeight);

    return 0;
}