【发布时间】:2014-04-28 12:23:50
【问题描述】:
我似乎找不到我用伪代码编写的以下代码的问题。该函数接收带有好处的数组p[]、带有权重的数组w[]、Weight - max weight、size (number of items) 和val (to be returned)。请帮忙!谢谢你。我认为问题可能与动态数组或循环有关。
int bruteforce(int p[], int w[], int size, int Weight, int val){
int k, i, j, tempWeight, tempValue;
int *A = (int*)calloc(size, sizeof(int));
for (i = 0; i < pow(2, size); i++)
j = size;
tempWeight = 0;
tempValue = 0;
while (A[j] != 0 && j > 0) {
A[j] = 0;
j = j - 1;
}
A[j] = 1;
for (k = 0; k < size;k++)
if (A[k] = 1)
tempWeight = tempWeight + w[k];
tempValue = tempValue + p[k];
if ((tempValue>val) && (tempWeight <= Weight))
val = tempValue;
return val;
}
【问题讨论】:
-
你有逻辑错误还是编译错误?
-
假设一个背包有两个物品。函数的每条语句应该执行多少次?使用您的调试器或在重要位置插入
printf。在你修复它之后,A在每次迭代中应该假设什么值?使用您的调试器或在重要位置插入printf。 -
谢谢!我遇到了逻辑错误,结果证明是错误的编码。
标签: c brute-force knapsack-problem