package program;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class Backpack {
public static void main(String[] args) {
// TODO 自动生成的方法存根
File file1 = new File("Knapsack.txt");
File file2 = new File("KnapsackResult.txt");
int k[][] = new int[6][2];
int K[][] = new int[16][6];
String str;
int tempchar;
try {
FileReader in = new FileReader(file1);
BufferedReader bufr = new BufferedReader(in);
FileWriter fw = new FileWriter(file2);
BufferedWriter bufw = new BufferedWriter(fw);
str = "";
int a = 0, b = 0, i = 0;
while ((tempchar = bufr.read()) != -1) {
str = str + (char) tempchar;
if ((char) tempchar == ' ') {
a = Integer.parseInt(str.trim());
str = "";
}
if ((char) tempchar == '\n') {
b = Integer.parseInt(str.trim());
k[i][0] = a;
k[i][1] = b;
str = "";
i++;
}
}
for(int j = 1; j < 6; j++) {
for(int w = 1; w < 16; w++) {
if(k[j][0] > w) {
K[w][j] = K[w][j-1];
}
else if(K[w][j-1] > (K[w-k[j][0]][j-1]+k[j][1])) {
K[w][j] = K[w][j-1];
}
else
K[w][j] = K[w-k[j][0]][j-1]+k[j][1];
}
}
str="";
tempchar = 32;
for(int x = 0; x < 16; x++) {
for(int y = 0; y < 6; y++) {
System.out.print(K[x][y]+" ");
str=str+Integer.toString(K[x][y])+(char) tempchar;
if(y==5){
bufw.write(str);
bufw.newLine();
str="";
}
}
System.out.println();
}
bufr.close();
in.close();
bufw.close();
fw.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
第7周作业1——背包问题
最新推荐文章于 2024-08-27 12:22:52 发布