可分割背包问题很容易理解,只需要根据收益和重量的比值进行排序,首选比值较大者填入即可,若物品种类大于剩余载重量,则填充剩余载重量的此物品,在剩余载重量足够的情况下,依次将物品填入背包即可。
import java.util.*;
public class Beibao {
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int num=Integer.parseInt(in.nextLine());
List b=new ArrayList<B>();
for(int i=0;i<num;i++){
String str=in.nextLine();
String s[]=str.split(" ");
b.add(new B(s[0].charAt(0),Double.parseDouble(s[1]),Double.parseDouble(s[2])));
}
for(int i=0;i<num;i++){
B temp=(B)b.get(i);
System.out.println(temp.ch+" "+temp.weight+" "+temp.value);
}
System.out.println();
Collections.sort(b, new Comparator<B>() {
@Override
public int compare(B o1, B o2) {
if(o1.bi-o2.bi>0){
return -1;
}else{
return 1;
}
}
});
for(int i=0;i<num;i++){
B temp=(B)b.get(i);
System.out.println(temp.ch+" "+temp.weight+" "+temp.value+" "+temp.bi);
}
int M=Integer.parseInt(in.nextLine());
double money=0;
for(int i=0;i<num && M>0;i++){
B temp=(B)b.get(i);
if(M-temp.weight>=0){
money+=temp.value;
M-=temp.weight;
}else{
money+=M*temp.bi;
M=0;
}
}
System.out.println(money);
}
}
class B{
char ch;
double weight;
double value;
double bi;
B(char ch1,double weight1,double value1){
ch=ch1;
weight=weight1;
value=value1;
bi=value/weight1;
}
}