您的位置:首页 > 其它

01背包问题

2016-09-08 20:03 417 查看
public class Knapsack {
public static void main(String[] args) {
int[] goodsWeight = new int[]{12, 2 , 1, 4, 1};
int[] goodsValue = new int[]{4, 2, 1, 10, 2};
int containWeight = 15, tempWeight, maxValue = 0, tempValue, weight = 0, tempKey;
for (int i = 0; i < Math.pow(2, goodsWeight.length); i++) {
tempKey = i;
tempValue = 0;
tempWeight = 0;
for (int j = 0; j < goodsWeight.length; j++) {
if (tempKey%2 == 1) {
tempValue += goodsValue[j];
tempWeight += goodsWeight[j];
}
tempKey /= 2;
}

if (maxValue < tempValue && tempWeight <= 15 ) {
maxValue = tempValue;
weight = i;
}
}

for (int i = 0; i < goodsWeight.length; i++) {
if (weight%2 == 1)
System.out.print(" " + goodsWeight[i]);
weight /= 2;
}
System.out.println("\n" + maxValue);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: