package org.wjp;
import java.util.ArrayList;
import java.util.List;
/**
* @author wujunpei
*/
public class Main {
public static void main(String[] args) {
List<Thing> things = new ArrayList<>();
int maxWeight = 6;
things.add(new Thing("水", 3, 10));
things.add(new Thing("书", 1, 3));
things.add(new Thing("食物", 2, 9));
things.add(new Thing("夹克", 2, 5));
things.add(new Thing("相机", 1, 6));
int[][] array = new int[things.size()][maxWeight];
String[][] whatThings = new String[things.size()][maxWeight];
for (int i = 0; i < things.size(); i++) {
Thing nowThing = things.get(i);
for (int j = 0; j < maxWeight; j++) {
int nowValue = nowThing.weight <= (j + 1) ? nowThing.value : 0;
int nowWeight = nowThing.weight <= (j + 1) ? nowThing.weight : 0;
int restValue = (i < 1 || j - nowWeight < 0) ? 0 : array[i - 1][j - nowWeight];
String restName = (i < 1 || j - nowWeight < 0) ? "" : whatThings[i - 1][j - nowWeight];
int nowWeightValueWithoutNowThing = i < 1 ? 0 : array[i - 1][j];
String nowNameValueWithoutNowThing = i < 1 ? "" : whatThings[i - 1][j];
if (nowWeightValueWithoutNowThing >= nowValue + restValue) {
array[i][j] = nowWeightValueWithoutNowThing;
whatThings[i][j] = nowNameValueWithoutNowThing;
} else {
array[i][j] = nowValue + restValue;
whatThings[i][j] = nowThing.name + ("".equals(restName) ? "" : "、" + restName);
}
}
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.printf("%4d", array[i][j]);
}
System.out.println();
}
for (int i = 0; i < whatThings.length; i++) {
for (int j = 0; j < whatThings[i].length; j++) {
System.out.printf("\t%s\t", whatThings[i][j].equals("") ? "无" : whatThings[i][j]);
}
System.out.println();
}
}
static class Thing {
String name;
int weight;
int value;
public Thing(String name, int weight, int value) {
this.name = name;
this.weight = weight;
this.value = value;
}
}
}
【Java】背包问题
最新推荐文章于 2024-03-30 11:05:24 发布