import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class FruitPacking {
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, Comparator.comparingDouble(f -> -f.getValuePerWeight()));
int capacity = 20;
int totalValue = 0;
List<PackedFruit> packedFruits = new ArrayList<>();
for (Fruit fruit : fruits) {
if (capacity > 0) {
String name = fruit.getName();
int weight = fruit.getWeight();
int value = fruit.getValue();
if (weight <= capacity) {
packedFruits.add(new PackedFruit(name, weight));
capacity -= weight;
totalValue += value;
} else {
double fraction = (double) capacity / weight;
packedFruits.add(new PackedFruit(name, weight * fraction));
totalValue += value * fraction;
capacity = 0;
}
}
}
System.out.println("装入背包的水果和它们的重量: " + packedFruits);
System.out.println("背包中水果的总价值: " + totalValue);
}
}
class Fruit {
private String name;
private int weight;
private int value;
public Fruit(String name, int weight, int value) {
this.name = name;
this.weight = weight;
this.value = value;
}
public String getName() {
return name;
}
public int getWeight() {
return weight;
}
public int getValue() {
return value;
}
public double getValuePerWeight() {
return (double) value / weight;
}
}
class PackedFruit {
private String name;
private double weight;
public PackedFruit(String name, double weight) {
this.name = name;
this.weight = weight;
}
@Override
public String toString() {
return "(" + name + ", " + weight + "kg)";
}
}