public class BagProblem {
public static void main(String[] args) {
Product[] products = init();
bagProblem(products,20);
bagProblem(products,30);
bagProblem(products,10);
}
public static void bagProblem(Product[] products, int target) {
int maxweight=0;
int maxprice=0;
for (int i = 0; i < 8; i++) {
int weight = 0;
int price = 0;
int j = i;
int z = products.length-1;
while (j>0){
if((j&1)==1){
weight+=products[z].weight;
price+=products[z].price;
}
j>>=1;
z--;
}
if(weight<=target&&price>maxprice){
maxprice = price;
maxweight = weight;
}
}
System.out.println("背包重量是"+target+"的背包,最优价格:"+maxprice+";重量:"+maxweight);
}
private static Product[] init() {
Product[] products = new Product[3];
products[0] = new Product("电脑", 5, 2000);
products[1] = new Product("手机", 5, 500);
products[2] = new Product("平板", 15, 1000);
return products;
}
}
class Product {
String name;
int weight;
int price;
public Product(String name, int weight, int price) {
this.name = name;
this.weight = weight;
this.price = price;
}
public Product(int weight, int price) {
this.weight = weight;
this.price = price;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}