第7周作业1——背包问题
来源:互联网 发布:歌曲相遇网络高安 编辑:程序博客网 时间:2024/04/29 21:49
代码:
package algorithm;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.util.StringTokenizer;public class Knapsack {private static int MAX_WEIGHT;private static int NUM;private static int[][] data;private static int[][] goods;private static void getGoodsData() {BufferedReader reader;try {File file = new File("src/dataFile/Knapsack.txt");reader = new BufferedReader(new FileReader(file));StringTokenizer tokenizer = new StringTokenizer(reader.readLine().trim());MAX_WEIGHT = Integer.valueOf(tokenizer.nextToken());NUM = Integer.valueOf(tokenizer.nextToken());goods = new int[NUM][2];String temp = null;int currentIndex = 0;while ((temp = reader.readLine()) != null) {tokenizer = new StringTokenizer(temp);int index = 0;while (tokenizer.hasMoreElements()) {goods[currentIndex][index] = Integer.valueOf(tokenizer.nextToken());index++;}currentIndex++;}} catch (Exception e) {e.printStackTrace();}}private static void initData() {data = new int[MAX_WEIGHT + 1][NUM + 1];for (int i = 0; i < MAX_WEIGHT + 1; i++) {for (int j = 0; j < NUM + 1; j++) {data[i][j] = 0;}}}public static void calculate() {boolean isTaked[] = new boolean[5];for (int i = 0; i < 5; i++) {isTaked[i] = false;}for (int j = 1; j <= NUM; j++) {for (int w = 1; w <= MAX_WEIGHT; w++) {if (goods[j - 1][0] > w) {data[w][j] = data[w][j - 1];} else {data[w][j] = getMax(data[w][j - 1], data[w - goods[j - 1][0]][j - 1] + goods[j - 1][1]);}}}}private static int getMax(int x, int y) {if (x > y) {return x;} else {return y;}}private static void write2File() {FileWriter output = null;try {output = new FileWriter(new File("src/dataFile/KnapsackResult.txt"));for (int i=0; i<data.length; i++) {for (int j=0; j<data[i].length; j++) {output.write(data[i][j] + "\t\t");}output.write("\n");}output.flush();} catch (Exception e) {e.printStackTrace();} finally {try {output.close();} catch (Exception e) {e.printStackTrace();}}}public static void main(String[] args) {// 获取物品的重量和价值getGoodsData();// 初始化data数组表initData();//计算二维表calculate();//输出结果文件write2File();}}
运行结果:
0 0
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题。
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题
- 第7周作业1——背包问题。
- 第7周作业1——背包问题
- 淘宝大牛们——晒一晒淘宝网技术内幕
- 20140422的星期二
- left join 关联条件位置
- Android开发学习笔记:Notification和NotificationManager浅析
- OpenCV编程->HOG检测(2)
- 第7周作业1——背包问题
- 【转】setTimeout和setInterval的区别你真的了解吗?
- Java7语法新特性:
- JNI学习积累之一 ---- 常用函数大全
- 使用Android自带的图标以及图标集合
- 解决ubuntu12.04 安装wineQQ后一直提示密码错误问题
- qt正则表达式小例子.
- AJAX实现文件下载的三种方式
- 在Exchange2007通过发件人信誉来过滤垃圾邮件