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); } }
相关文章推荐
- LBF特征和增强的LBF特征。
- 一个简单的Android Library Project例子
- 【c++11】 练习 std::bind & lambda
- R语言的一些笔记
- testng并发测试与测试并发
- XML的解析
- Linux内核分析:页回收导致的cpu load瞬间飙高的问题分析与思考
- 对String值不可变的理解以及String类型的引用传递问题
- laravel框架目录结构
- 输出1到某个整数范围中所有的完数
- debug和release的不同结果
- Android学习笔记之Intent
- 在linux下安装minicom
- Microsoft SQL Server,错误2
- Win8系统下安装Oracle11g时,安装程序报错:[INS-13001]环境不满足最低要求的解决方法
- PHP Pthread多线程操作
- 八皇后问题
- common-pool2 讲解。
- button tast
- POJ 1006 生理周期(水)