第七周作业——背包问题

作业要求: 对数据文件Knapsack.txt(第一行为背包总重量15,物品数量5;第2-6行,分别为第1-5件物品的重量与价值,W=15) , 编程计算最终背包所装物品的编号、总重量与总价值。要求能够把构造的二维表格输出到文件KnapsackResult.txt中。

数据文件如下图所示:


源代码如下面所示:

package week_7;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;


public class Knapsack2 {
	private static int MAX_WEIGHT;    //背包可容纳的最大容量
	private static int NUM;           //背包物品的数量
	private static int[][] data;       //物品的二维表格
	private static int[][] goods;      //物品的重量和价值二维

	
	//计算背包问题的二维表格
	public static void getDataArray() {
		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 getIsTaked() {
		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) {
		return x>y ? x : y;
	}
	
	//输出结果文件
	private static void writeToFile() {
		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) throws IOException {
		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++;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		getDataArray();

		//计算二维表
		getIsTaked();
		
		//输出结果文件
		writeToFile();
	}
}


写入结果到文件如下图所示:


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值