我需要以递归、内存和动态编程的方式解决背包问题。目前我陷入了递归方法。
问题是我实际上不确定我的代码是否做了它应该做的事情(而且我也不知道如何检查)。我根据在互联网上其他地方找到的代码改编了代码。
问题涉及利润和质量。每个商品都与利润和质量相关,可用商品数量为 MAX_N(数量),质量为 MAX_CAPACITY。目的是让背包里有尽可能多的“利润”。
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define MAX_N 10
#define MAX_CAPACITY 165
int m[MAX_N][MAX_CAPACITY];
int knapsackRecursive(int capacity, int mass[], int profit[], int n) {
if (n < 0)
return 0;
if (profit[n] > capacity)
return knapsackRecursive(capacity, mass, profit, n-1);
else
return MAX(knapsackRecursive(capacity, mass, profit, n-1), knapsackRecursive(capacity - mass[n], mass, profit, n-1) + profit[n]);
}
int knapsackMemoized(int capacity, int mass[], int profit[], int n) {
}
int knapsackDynamic(int capacity, int mass[], int profit[], int n) {
}
void test() {
int M1[4] = {6, 3, 2, 4};
int P1[4] = {50, 60, 40, 20};
int M2[10] = {23, 31, 29, 44, 53, 38, 63, 85, 89, 82};
int P2[10] = {92, 57, 49, 68, 60, 43, 67, 84, 87, 72};
// a)
knapsackRecursive(MAX_CAPACITY, M1, P1, MAX_N);
knapsackRecursive(MAX_CAPACITY, M2, P2, MAX_N);
// b)
knapsackMemoized(MAX_CAPACITY, M1, P1, MAX_N);
knapsackMemoized(MAX_CAPACITY, M2, P2, MAX_N);
// c)
knapsackDynamic(MAX_CAPACITY, M1, P1, MAX_N);
knapsackDynamic(MAX_CAPACITY, M2, P2, MAX_N);
}
int main() {
test();
}
正如我所提到的,我实际上不确定如何首先检查计算是否正确(例如,在哪里插入调试 printf()
's)。我尝试打印 M1/P1 的最终结果,结果是“170”,我认为这是不正确的。
编辑:这是练习提供的示例:
Example: Given a knapsack of capacity 5, and items with mass[] = {2, 4, 3, 2} and profit profit[] = {45, 40, 25, 15}, the best combination would be item 0 (with mass 2 and profit 45) and item 2 (with mass 3 and with profit 25) for a total profit of 70. No other combination with mass 5 or less has a greater profit.
最佳答案
程序不正确,请参见这一行:
if (profit[n] > capacity)
return knapsackRecursive(capacity, mass, profit, n-1);
在这里,您可以将利润与产能进行比较。您应该与mass[n]
进行比较。其余代码目前看起来没问题。
也许您最好使用库的最大值而不是“三元运算符”,因为此类运算符会创建分支,而有时可以在不分支的情况下完成最大值。
您也许可以尝试解决的程序问题至少是生成袋子并打印它。您还可以将背包问题的实例与已知的解决方案结合使用。
关于c - 在C中递归解决背包问题时遇到麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30140545/