题目阅览
“嘟嘟嘟嘟嘟嘟
喇叭响
我是汽车小司机
我是小司机
我为祖国运输忙
运输忙”
这是儿歌“快乐的小司机”。话说现在当司机光有红心不行,还要多拉快跑。多拉不是超载,是要让所载货物价值最大,特别是在当前油价日新月异的时候。司机所拉货物为散货,如大米、面粉、沙石、泥土…
现在知道了汽车核载重量为w,可供选择的物品的数量n。每个物品的重量为gi,价值为pi。求汽车可装载的最大价值。(n<10000,w<10000,0<gi<=100,0<=pi<=100)
输入格式
输入第一行为由空格分开的两个整数n w
第二行到第n+1行,每行有两个整数,由空格分开,分别表示gi和pi
输出格式
最大价值(保留一位小数)
样例输入1
5 36
99 87
68 36
79 43
75 94
7 35
样例输出1
71.3
样例说明
先装第5号物品,得价值35,占用重量7
再装第4号物品,得价值36.346,占用重量29
最后保留一位小数,得71.3
思路简介
这道题首先需要得出每种物品单位重量的价值,在此使用结构体数组存储所有物品的总重量、总价值和单位价值,然后根据单位价值大小降序排序,最后根据能容纳重量来判断最优物品的价值,得出最终结果。
快乐司机实现代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct goods{
int weight;
int value;
float perValue;
};
bool compare(goods temp1,goods temp2){
return temp1.perValue>temp2.perValue;
}
int main(){
int n,w;
cin>>n>>w;
vector<goods> goodsList;
for(int i=0;i<n;i++){
goods tempGoods;
cin>>tempGoods.weight>>tempGoods.value;
tempGoods.perValue = tempGoods.value*1.00/tempGoods.weight;
goodsList.push_back(tempGoods);
}
sort(goodsList.begin(),goodsList.end(),compare);
int countWeight=0;
float maxValue=0;
for(int j=0;j<n;j++){
if(goodsList[j].weight<=w-countWeight){
countWeight += goodsList[j].weight;
maxValue += goodsList[j].value;
}else{
maxValue += (w-countWeight)*goodsList[j].perValue;
countWeight+=w-countWeight;
}
if(countWeight==w){
break;
}
}
printf("%.1f",maxValue);
return 0;
}
运行截图