编辑代码

#include <stdio.h>
#include <stdbool.h>

#define MAX_ITEMS 5

int maxProfit = 0;
int maxWeight = 10;
int totalItems = 5;
int items[MAX_ITEMS][2] = {
    {6, 2},
    {10, 3},
    {12, 4},
    {8, 5},
    {9, 6}
};
bool selectedItems[MAX_ITEMS];

void backtrack(int index, int currentProfit, int currentWeight) {
    if (currentWeight > maxWeight) {
        return;
    }

    if (currentProfit > maxProfit) {
        maxProfit = currentProfit;
    }

    if (index == totalItems) {
        return;
    }

    selectedItems[index] = true;
    backtrack(index + 1, currentProfit + items[index][0], currentWeight + items[index][1]);

    selectedItems[index] = false;
    backtrack(index + 1, currentProfit, currentWeight);
}

int main() {
    backtrack(0, 0, 0);

    printf("Maximum profit: %d\n", maxProfit);

    printf("Selected items:\n");
    for (int i = 0; i < totalItems; i++) {
        if (selectedItems[i]) {
            printf("Item %d\n", i + 1);
        }
    }

    return 0;
}