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();
}
}
第七周作业——背包问题
最新推荐文章于 2021-11-27 17:10:50 发布