【hdoj_2187】老人是真饿了

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2187


题意:由很多种价格的大米,在经费一定的情况下,买重量更多的大米,并且题目假设经费买不光所有的大米.


思路:贪心法,先买价格低的,再买价格高的.所以先按照价格递增将大米排序(结构体排序),然后消耗经费,至到经费用完.


C++代码如下

#include<iostream>
#include<algorithm>
#include<iomanip>
using namespace std;

struct Rice//大米有价格、重量两个属性 
{
	int p,h;	
};

bool cmp(Rice r1,Rice r2)//用于结构体排序 
{
	return r1.p < r2.p;
}

int main()
{
	int C;
	cin >> C;//测试的数据有C组 
	while(C--)
	{
		int n,m;
		cin >> n >> m;
		Rice * r = new Rice[m];
		for(int i=0;i<m;i++)
			cin >> r[i].p >> r[i].h;//输入大米价格和重量 
		sort(r,r+m,cmp);//排序 
		double result = 0.0;//能买到的大米的最大重量,用double 
		for(int i=0;i<m;i++)
		{
			if(n==0)	break;
			if(n>r[i].p * r[i].h)
			{
				result += r[i].h;
				n -= r[i].p * r[i].h;
			}
			else
			{
				result += (double)(n) / r[i].p;
				break; //经费用完了,退出 
			}
		}
		cout << setprecision(2) << fixed << result << endl;//两位小数(#include<iomanip>) 
	}
	
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值