import java.util.Arrays;
import java.util.Comparator;
public class BeanKnapsack {
static class Bean {
int weight;
int value;
public Bean(int weight, int value) {
this.weight = weight;
this.value = value;
}
}
public static double maxBeanValue(Bean[] beans, int capacity) {
Arrays.sort(beans, Comparator.comparingDouble(bean -> (double) bean.value / bean.weight));
double maxValue = 0;
for (int i = beans.length - 1; i >= 0; i--) {
if (capacity >= beans[i].weight) {
maxValue += beans[i].value;
capacity -= beans[i].weight;
} else {
maxValue += (double) beans[i].value / beans[i].weight * capacity;
break;
}
}
return maxValue;
}
public static void main(String[] args) {
Bean[] beans = {new Bean(2, 10), new Bean(3, 5), new Bean(5, 15), new Bean(7, 7), new Bean(1, 6)};
int capacity = 15;
double result = maxBeanValue(beans, capacity);
System.out.println("(20052248田雨瑶)背包中豆子的最大值: " + result);
}
}