背包问题
来源:互联网 发布:网络运维 编辑:程序博客网 时间:2024/06/11 05:30
package 二〇一七年三月二十四日;import java.util.Arrays;public class 背包问题 { public static void main(String args[]) { double M = 10; // 定义背包容量为10 Goods[] g = new Goods[10]; // 定义10个物品 g[0] = new Goods(2, 1.4); // Goods(容量, 价值) g[1] = new Goods(1.2, 5); g[2] = new Goods(2.1, 3); g[3] = new Goods(2.4, 4); g[4] = new Goods(1.8, 1.4); g[5] = new Goods(2.2, 6); g[6] = new Goods(1.1, 1); g[7] = new Goods(1.5, 3); g[8] = new Goods(1.1, 0.9); g[9] = new Goods(2, 2); System.out.println("物体未排序前的价值容量比(value/volume):"); for (Goods e : g) { System.out.printf("%-8.1f", e.value / e.volume); } System.out.println(); System.out.println("物体排序后的价值容量比(value/volume):"); Arrays.sort(g); for (Goods e : g) { System.out.printf("%-8.1f", e.value / e.volume); } System.out.println(); double[] x = new double[10]; // 存储每个物品放入背包的程度,0<=x<=1 int i = 0; while (M != 0 && i < g.length) { if (g[i].volume <= M) { x[i] = 1; M -= g[i].volume; ++i; } else { x[i] = M / g[i].volume; M = 0; } } System.out.println("贪心策略解决背包放入物品问题:"); for (i = 0; i < 10; ++i) System.out.printf("#%d:%-5.1f \n", i, x[i]); System.out.println(); }}class Goods implements Comparable<Goods> { public double volume = 0; public double value = 0; public Goods(double vol, double val) { volume = vol; value = val; } public int compareTo(Goods other) { if (value / volume < other.value / other.volume) return 1; if (value / volume > other.value / other.volume) return -1; return 0; }}
阅读全文
0 0
- 【无限背包】背包问题
- 背包问题---01背包
- 背包问题--部分背包
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- 背包问题
- Java判断字符串是否是乱码(亲测可用)
- Java学习路线
- 不可滑动的ViewPager
- 广播接收者拦截电话
- MySQL
- 背包问题
- J2EE系列之SpringMVC学习笔记(三)--SpringMVC控制器
- 20170608_STL 中vector 容器的一些常用函数,vector和数组的比较
- 提示Android requires compiler compliance level 5.0 or 6.0.&nb
- 网页制作HTML代码全攻略
- 蓝桥杯-调和级数
- 集成三方地图时如何获取SHA1值,以及keytool异常问题解决方法
- spring + springMVC声明式事务失效问题
- 8皇后问题