import java.util.Arrays;
public class FractionalKnapsack {
static class Fruit implements Comparable<Fruit> {
String name;
int weight;
int value;
double valuePerKg;
Fruit(String name, int weight, int value) {
this.name = name;
this.weight = weight;
this.value = value;
this.valuePerKg = (double) value / weight;
}
public int compareTo(Fruit other) {
return Double.compare(other.valuePerKg, this.valuePerKg);
}
}
public static void fillKnapsack(Fruit[] fruits, int capacity) {
Arrays.sort(fruits);
int currentWeight = 0;
double totalValue = 0;
for (Fruit fruit : fruits) {
if (currentWeight + fruit.weight <= capacity) {
currentWeight += fruit.weight;
totalValue += fruit.value;
System.out.println("装100%" + fruit.name);
} else {
double fraction = (double) (capacity - currentWeight) / fruit.weight;
totalValue += fraction * fruit.value;
System.out.printf("装%.2f%%%s\n", fraction * 100, fruit.name);
break;
}
}
System.out.println("总价值: " + totalValue);
}
public static void main(String[] args) {
Fruit[] fruits = {
new Fruit("苹果", 15, 300),
new Fruit("香蕉", 18, 180),
new Fruit("橘子", 10, 150),
new Fruit("猕猴桃", 9, 270)
};
fillKnapsack(fruits, 20);
}
}