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);
}
}
01背包问题
最新推荐文章于 2022-07-27 23:29:34 发布