import java.util.*;
public class Backpack {
public static void main(String[] args) {
List<Fruit> fruits = new ArrayList<>();
fruits.add(new Fruit("苹果", 15, 300));
fruits.add(new Fruit("香蕉", 18, 180));
fruits.add(new Fruit("橘子", 10, 150));
fruits.add(new Fruit("猕猴桃", 9, 270));
Collections.sort(fruits, new Comparator<Fruit>() {
@Override
public int compare(Fruit f1, Fruit f2) {
double v1 = f1.value / f1.weight;
double v2 = f2.value / f2.weight;
if (v1 > v2) {
return -1;
} else {
return 1;
}
}
});
double capacity = 20;
double totalWeight = 0;
double totalValue = 0;
for (Fruit fruit : fruits) {
if (totalWeight + fruit.weight <= capacity) {
totalWeight += fruit.weight;
totalValue += fruit.value;
System.out.println("装入" + fruit.name + ",重量:" + fruit.weight + "kg,价值:" + fruit.value + "元");
} else {
double remain = capacity - totalWeight;
totalWeight += remain;
totalValue += (remain / fruit.weight) * fruit.value;
System.out.println("装入部分" + fruit.name + ",重量:" + remain + "kg,价值:" + (remain / fruit.weight) * fruit.value + "元");
break;
}
}
System.out.println("背包中装入的水果总重量为:" + totalWeight + "kg");
System.out.println("背包中装入的水果总价值为:" + totalValue + "元");
}
}
class Fruit {
String name;
double weight;
double value;
public Fruit(String name, double weight, double value) {
this.name = name;
this.weight = weight;
this.value = value;
}
}