sách gpt4 ai đã đi

Triển khai C++ của Knapsack Branch và Bound

In lại 作者:可可西里 更新时间:2023-11-01 17:38:19 30 4
mua khóa gpt4 Nike

我正在尝试使用分支定界的 C++ 实现这个背包问题。此网站上有一个 Java 版本:Implementing branch and bound for knapsack

我试图让我的 C++ 版本打印出它应该打印出的 90,但它并没有这样做,而是打印出 5。

有谁知道问题出在哪里?

#include 
#include
sử dụng không gian tên std;

struct node
{
int level;
int profit;
int weight;
int bound;
};

int bound(node u, int n, int W, vector pVa, vector wVa)
{
int j = 0, k = 0;
int totweight = 0;
int result = 0;

if (u.weight >= W)
{
trả về 0;
}
khác
{
result = u.profit;
j = u.level + 1;
totweight = u.weight;

while ((j < n) && (totweight + wVa[j] <= W))
{
totweight = totweight + wVa[j];
result = result + pVa[j];
j++;
}

k = j;

if (k < n)
{
result = result + (W - totweight) * pVa[k]/wVa[k];
}
trả về kết quả;
}
}

int knapsack(int n, int p[], int w[], int W)
{
queue Q;
node u, v;
vector pV;
vector wV;
Q.empty();

for (int i = 0; i < n; i++)
{
pV.push_back(p[i]);
wV.push_back(w[i]);
}

v.level = -1;
v.profit = 0;
v.weight = 0;

int maxProfit = 0;

//v.bound = bound(v, n, W, pV, wV);
Q.push(v);

while (!Q.empty())
{
v = Q.front();
Q.pop();

if (v.level == -1)
{
u.level = 0;
}
else if (v.level != (n - 1))
{
u.level = v.level + 1;
}

u.weight = v.weight + w[u.level];
u.profit = v.profit + p[u.level];

u.bound = bound(u, n, W, pV, wV);

if (u.weight <= W && u.profit > maxProfit)
{
maxProfit = u.profit;
}

if (u.bound > maxProfit)
{
Q.push(u);
}

u.weight = v.weight;
u.profit = v.profit;

u.bound = bound(u, n, W, pV, wV);

if (u.bound > maxProfit)
{
Q.push(u);
}
}
return maxProfit;
}

int chính()
{
int maxProfit;
int n = 4;
int W = 16;
int p[4] = {2, 5, 10, 5};
int w[4] = {40, 30, 50, 10};

cout << knapsack(n, p, w, W) << endl;

system("PAUSE");
}

1 Câu trả lời

我认为您将利润和权重值放在了错误的 vector 中。变化:

int p[4] = {2, 5, 10, 5};
int w[4] = {40, 30, 50, 10};

到:

int w[4] = {2, 5, 10, 5};
int p[4] = {40, 30, 50, 10};

你的程序将输出 90。

关于背包分支定界的C++实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11498035/

30 4 0
可可西里
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com