分支定界背包 Java
Posted
技术标签:
【中文标题】分支定界背包 Java【英文标题】:Branch and Bound Knapsack Java 【发布时间】:2015-11-22 19:41:03 【问题描述】:import java.io.*;
import java.util.*;
class node
int level;
int profit;
int weight;
int bound;
public class KnapsackBB
public static void main(String args[])throws Exception
int maxProfit;
int N;
int W;
int wt;
int vl;
int maxVal;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of items: ");
N = input.nextInt();
System.out.println("Please enter the capacity of the Knapsack: ");
W = input.nextInt();
int[] Vl = new int[N];
int[] Wt = new int[N];
for(int i = 0; i < N; i++)
System.out.println("Please enter the weight anc value of item " + i + ": ");
wt = input.nextInt();
vl = input.nextInt();
Wt[i] = wt;
Vl[i] = vl;
//for(int i = 0; i < 1000; i++)
maxVal = knapsack(N, Vl, Wt, W);
//
System.out.println(maxVal);
public static int bound(node u, int n, int W, int[] pVa, int[] wVa)
int j = 0, k = 0;
int totweight = 0;
int result = 0;
if (u.weight >= W)
return 0;
else
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];
return result;
public static int knapsack(int n, int[] p, int[] w, int W)
Queue<node> Q = new LinkedList<node>();
node u = new node();
node v = new node();
int[] pV = new int[p.length];
int[] wV = new int[w.length];
Q.poll();
for (int i = 0; i < n; i++)
pV[i] = p[i];
wV[i] = w[i];
v.level = -1;
v.profit = 0;
v.weight = 0;
int maxProfit = 0;
//v.bound = bound(v, n, W, pV, wV);
Q.add(v);
while (Q.size() > 0)
v = Q.remove();
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.add(u);
u.weight = v.weight;
u.profit = v.profit;
u.bound = bound(u, n, W, pV, wV);
if (u.bound > maxProfit)
Q.add(u);
return maxProfit;
我的程序有问题,因为我得到了错误的输出。我已经从我在网上找到的另一个程序从 C++ 转换并且它可以正常工作。
输入:
4
6
2 10
3 12
4 5
3 15
输出应该是:
22
得到的输出:
12
【问题讨论】:
【参考方案1】:您的复制技巧还有很多不足之处 - 如果您添加了指向原始来源的链接,那将会很有帮助。
好像你已经添加了行
u.weight = v.weight;
u.profit = v.profit;
u.bound = bound(u, n, W, pV, wV);
if (u.bound > maxProfit)
Q.add(u);
两次。至少这提供了您正在寻找的“22”答案。
也就是说,该解决方案远非面向对象和一般的 Java 风格。
【讨论】:
以上是关于分支定界背包 Java的主要内容,如果未能解决你的问题,请参考以下文章