作业要求: 对数据文件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();
}
}
写入结果到文件如下图所示: