/* 物品只有放进背包和不放进背包两种选择,枚举所有可能的组合,复杂度是O(2^numOfItems) */
#include <stdio.h>
#define MAX_ITEMS 101
#define MAX_WEIGHT 101
int weight[MAX_ITEMS];
int value[MAX_ITEMS];
int weightLimit;
int numOfItems;
int result;
void packTheItemOrNot(int itemNum, int currentWeight, int currentValue){
if (itemNum > numOfItems)
return;
int newWeight = currentWeight + weight[itemNum];
if (newWeight <= weightLimit){
int newValue = currentValue + value[itemNum];
if (newValue > result)
result = newValue;
packTheItemOrNot(itemNum + 1, newWeight, newValue);
}
packTheItemOrNot(itemNum + 1, currentWeight, currentValue);
}
void zeroOneKnapsackV1(){
packTheItemOrNot(1, 0, 0);
}
int main(){
scanf("%d%d", &numOfItems, &weightLimit);
int item;
for (item = 1; item <= numOfItems; item++)
scanf("%d%d", &weight[item], &value[item]);
zeroOneKnapsackV1();
printf("%d", result);
return 0;
}
/* 动态规划,复杂度是O(numOfItems * weightLimit) */
#include <stdio.h>
#define MAX_ITEMS 101
#define MAX_WEIGHT 101
int weight[MAX_ITEMS];
int value[MAX_ITEMS];
int weightLimit;
int numOfItems;
int result;
//maxValue[preItems][totalWeight]表示把“前”preItems件物品“恰”(不是完全)放进容量为totalWeight的背包能获得的最大价值
int maxValue[MAX_ITEMS][MAX_WEIGHT];
void zeroOneKnapsackV2(){
int preItems, totalWeight, tempValue;
for (preItems = 1; preItems <= numOfItems; preItems++)
for (totalWeight = 1; totalWeight <= weightLimit; totalWeight++){
if (weight[preItems] > totalWeight)
maxValue[preItems][totalWeight] = maxValue[preItems - 1][totalWeight];
else {
tempValue = maxValue[preItems - 1][totalWeight - weight[preItems]] + value[preItems];
if (tempValue > maxValue[preItems][totalWeight])
maxValue[preItems][totalWeight] = tempValue;
}
}
result = maxValue[numOfItems][weightLimit];
}
int main(){
scanf("%d%d", &numOfItems, &weightLimit);
int item;
for (item = 1; item <= numOfItems; item++)
scanf("%d%d", &weight[item], &value[item]);
zeroOneKnapsackV2();
printf("%d", result);
return 0;
}
/* 动态规划加空间优化 */
#include <stdio.h>
#define MAX_ITEMS 101
#define MAX_WEIGHT 101
#define MAX(x, y) ( (x) > (y) ? (x) : (y) )
int weight[MAX_ITEMS];
int value[MAX_ITEMS];
int weightLimit;
int numOfItems;
int result;
//如果求取的是“恰好装满背包时的最优解”,除maxValue[0]初始化为0之外,其他初始化为负无穷
int maxValue[MAX_WEIGHT];
void zeroOneKnapsackV3(){
int preItems, lowerWeight, totalWeight;
for (preItems = 1; preItems <= numOfItems; preItems++){
lowerWeight = weight[preItems];
//从大到小遍历totalWeight是为了优化maxValue的空间
for (totalWeight = weightLimit; totalWeight >= lowerWeight; totalWeight--)
maxValue[totalWeight] = MAX(maxValue[totalWeight], maxValue[totalWeight - lowerWeight] + value[preItems]);
}
result = maxValue[weightLimit];
}
int main(){
scanf("%d%d", &numOfItems, &weightLimit);
int item;
for (item = 1; item <= numOfItems; item++)
scanf("%d%d", &weight[item], &value[item]);
zeroOneKnapsackV3();
printf("%d", result);
return 0;
}