0-1背包追溯

时间:2019-11-30 23:57:20

标签: c++ knapsack-problem

下面的代码是我正在尝试在回溯算法中构建0-1背包问题的代码,我尝试运行和调试了很多次,但仍然出现错误:EXC_BAD_ACCESS(code = EXC_I386_GPFLT) “如果(w [I]> = W)”。请让我知道错误是什么,我非常感谢任何评论。 谢谢。

代码如下:

bool promissing(int i, int profit, int weight, int n, int w[], int p[], int W, int maxProfit)
{
int j,k, totweight;
double bound;


//if weight is greater than W -> the bag can't hold the item we just took
// -> return False
if(w[i] >= W)
{
    return false;
}
else
{
    j = i + 1;
    bound = p[i];
    totweight = w[i];

    //Grab as many item as possible (not breaking the bag)
    while (j <= n && totweight + w[j] <= W)
    {
        totweight = totweight + w[j];
        bound = bound + p[j];
        j++;
    }
    k = j;
    if(k <= n)
    {
        bound = bound + (W - totweight) * p[k]/w[k]; //grab part of k item that can be fit in the bag

    }
}
return bound > maxProfit;

}

void knapsack_backtracking(int i, int profit, int weight, int n, int p[], int w[], int W, int maxProfit)
{
//int maxProfit = 0;
int bestSet[] = {};
int include[] = {};
int numBest;

//update maxProfit

if (weight <= W && profit > maxProfit)
{
    maxProfit = profit;
    numBest = i;
    //bestset = include;
    for(int m = 0; m < n; m++)
    {
        bestSet[m] = include[m];
    }
}

if(promissing(i, profit ,weight , n , w, p, W, maxProfit))
{
    include[i + 1] = 1; //steal item i+1
    knapsack_backtracking(i+1, profit + p[i], weight + w[i], n, p, w, W, maxProfit);
    include[i + 1] = 0;  //reject item i + 1
    knapsack_backtracking(i+1, profit, weight,n,p,w,W, maxProfit);
}

}

0 个答案:

没有答案