#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;
}