1.背包问题。对上文中提到的背包问题提供的表1(数据文件下载Knapsack.txt,第一行为背包总重量15,物品数量5;第2-6行,分别为第1-5件物品的重量与价值),W=15,编程计算最终背包所装物品的编号、总重量与总价值。要求能够把构造的二维表格输出到文件KnapsackResult.txt中。
- package javapage;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.ArrayList;
- public class Knapsack {
- static int count=0; //容量为15
- static int allweight=0;
- static int weight[]={0,0,0,0,0}; //物品的重量
- static int value[]={0,0,0,0,0}; //物品的价值
- static int result[]={-1,-1,-1,-1,-1};//初始化背包
- public static void main(String[] args) {
- String path = "Knapsack.txt";
- ArrayList<Integer> list = read(path);
- for(int i=2,j=0;i<list.size();i=i+2,j++){
- weight[j]=list.get(i);
- }
- for(int i=3,j=0;i<list.size();i=i+2,j++){
- value[j]=list.get(i);
- }
- //控制台打印
- Knapsack ks=new Knapsack();
- System.out.println("总价值:"+ks.Knapsacountk(list.get(1)-1,list.get(0)));
- System.out.print("物品编号:");
- ks.printNum();
- System.out.println();
- System.out.println("总重量:"+allweight);
- //写入txt
- ks.writeFile(result);
- }
- public void printNum(){
- for(int i=0;i<result.length;i++)
- {
- if(result[i]==1){
- System.out.print(i+1+",");
- allweight+=weight[i];
- }
- }
- }
- public void writeFile(int[] list) {
- File f = new File("KnapsackResult.txt");
- FileOutputStream fou = null;
- try {
- fou = new FileOutputStream(f);
- String s,a;
- a=new String("物品编号\t物品重量\t物品价值\t\n");
- for (int i = 0; i < list.length; i++) {
- if(list[i]==1){
- s = String.valueOf(list[i]);
- a += i+1+" \t" + weight[i] + " \t"+value[i]+" \t\n";
- }
- }
- fou.write(a.getBytes());
- fou.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public int Knapsacountk(int n ,int count)
- {
- if(n==-1||count==0)
- return 0;
- int tmp1=Knapsacountk(n-1,count);
- if(weight[n]>count)
- {
- result[n]=0;
- return tmp1;
- }
- int tmp2=value[n]+Knapsacountk(n-1,count-weight[n]);
- if(tmp1>tmp2)
- {
- result[n]=0;
- return tmp1;
- }
- result[n]=1;
- return tmp2;
- }
- // 读取文件到Arraylist 数组
- public static ArrayList read(String path) {
- ArrayList<Integer> list = new ArrayList<Integer>();
- BufferedReader input = null;
- try {
- FileReader in = new FileReader(path);
- input = new BufferedReader(in);
- String ss;
- while ((ss = input.readLine()) != null) {
- String[] s = (ss.split(" "));
- for (int i = 0; i < s.length; i++) {
- list.add(Integer.parseInt(s[i].trim()));
- }
- }
- in.close();
- input.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return list;
- }
- }