第七周作业——背包问题

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值