问题描述 “嘟嘟嘟嘟嘟嘟 喇叭响 我是汽车小司机 我是小司机 我为祖国运输忙 运输忙” 这是儿歌“快乐的小司机”。话说现在当司机光有红心不行,还要多拉快跑。多拉不是超载,是要让所载货物价值最大,特别是在当前油价日新月异的时候。司机所拉货物为散货,如大米、面粉、沙石、泥土…… 现在知道了汽车核载重量为w,可供选择的物品的数量n。每个物品的重量为gi,价值为pi。求汽车可装载的最大价值。(n<10000,w<10000,0
代码语言:javascript复制import java.util.Arrays;
import java.util.Scanner;
/*
* 典型的贪心算法的应用
*/
public class Main {
static class Value implements Comparable<Value>{
private int num;
private double value;
public Value(int num, double value) {
super();
this.num = num;
this.value = value;
}
public int getNum() {
return num;
}
public double getValue() {
return value;
}
public int compareTo(Value o) {
// TODO Auto-generated method stub
double cmp = this.value - o.value;
if ( cmp > 0.0){
return 1;
}else if ( cmp == 0.0){
return 0;
}else{
return -1;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int weight = in.nextInt();
double sum = 0;
Value[] Goods = new Value[n];
int g;
int p;
for (int i = 0 ; i < n ; i ){
g = in.nextInt();
p = in.nextInt();
Goods[i] = new Value(g, p*1.0/g);
}
Arrays.sort(Goods);
for ( int i = n-1 ; i >= 0 ; i--){
if ( weight > Goods[i].getNum()){
sum = Goods[i].getValue()*Goods[i].getNum();
weight -= Goods[i].getNum();
}else{
sum = weight*Goods[i].getValue();
break;
}
}
System.out.printf("%.1f",sum);
in.close();
}
}