问题描述
“嘟嘟嘟嘟嘟嘟
喇叭响
我是汽车小司机
我是小司机
我为祖国运输忙
运输忙”
这是儿歌“快乐的小司机”。话说现在当司机光有红心不行,还要多拉快跑。多拉不是超载,是要让所载货物价值最大,特别是在当前油价日新月异的时候。司机所拉货物为散货,如大米、面粉、沙石、泥土…
现在知道了汽车核载重量为w,可供选择的物品的数量n。每个物品的重量为gi,价值为pi。求汽车可装载的最大价值。(n<10000,w<10000,0<gi<=100,0<=pi<=100)
输入格式
输入第一行为由空格分开的两个整数n w
第二行到第n+1行,每行有两个整数,由空格分开,分别表示gi和pi
输出格式
最大价值(保留一位小数)
样例输入
5 36
99 87
68 36
79 43
75 94
7 35
样例输出
71.3
解释:
先装第5号物品,得价值35,占用重量7
再装第4号物品,得价值36.346,占用重量29
最后保留一位小数,得71.3
思路
就是一道简单的贪心题,就是要找到最高性价比的东西先使用,依次选下去,知道达到最大重量。。。。
代码
#include <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <cstring>
#include <cmath>
#include <vector>
#include <set>
#include <map>
using namespace std;
const int maxn=10050;
struct node{
double weight; //重量
double value; //价值
double avevalue; //单位重量的价值 ,类似单价
}sth[maxn];
int cmp(node a,node b) //排序方式,性价比高的在前
{
return a.avevalue>b.avevalue;
}
int main()
{
int n,w;
double ans=0;
cin>>n>>w;
for(int i=0;i<n;i++) //
{
cin>>sth[i].weight>>sth[i].value;
sth[i].avevalue=sth[i].value/sth[i].weight;
//计算出每个物品的性价比
}
sort(sth,sth+n,cmp); //排序
for(int i=0;i<n;i++)
{
if(sth[i].weight >= w)
/*如果当前物品重量大于总w,就全买这种东西,但是
要注意该物品的总价值是 单价*总w (因为只有那么多w)*/
{
ans += sth[i].avevalue*w;
break;
}
else//否则,小于总w,那就全买,直接加当前物品的全部价值
{
ans += sth[i].value;
w-=sth[i].weight; //总w减去当前物品占去的weight
}
}
printf("%.1f",ans); //按照格式输出
return 0;
}