老人真是饿了(贪心)

对于幸存的灾民来说,最急待解决的显然是温饱问题,救灾部队一边在组织人员全力打通交通,一边在组织采购粮食。现在假设下拨了一定数量的救灾经费要去市场采购大米(散装)。如果市场有m种大米,各种大米的单价和重量已知,请问,为了满足更多灾民的需求,最多能采购多少重量的大米呢?
 

Input
输入数据首先包含一个正整数C,表示有C组测试用例,每组测试用例的第一行是两个整数n和m(0<n<=1000,0<m<=1000),分别表示经费的金额和大米的种类,然后是m行数据,每行包含2个整数p和h(1<=p<=25,1<=h<=100),分别表示单价和对应大米的重量。
 

Output
对于每组测试数据,请输出能够购买大米的最多重量(你可以假设经费买不光所有的大米)。
每个实例的输出占一行,保留2位小数。
 

Sample Input
1
7 2
3 3
4 4
 

Sample Output
2.33
 

贪心算法   求解


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct st
{
	int price;
	int weight;
};


bool cmp(st a, st b)
{
	if (a.price == b.price){
		return a.weight > b.weight;
	}
	return a.price < b.price;
}

int main()
{
	int testDate;
	while (cin >> testDate){

		while (testDate--){
			vector<st> vec;
			int total, type;
			int price, weight;

			cin >> total >> type;
			vec.resize(type);
			for (int i = 0; i < type; i++){
				cin >> price >> weight;
				
				vec[i].price = price;
				vec[i].weight = weight;
			}
			sort(vec.begin(), vec.end(), cmp); //大米按价格排序

			
			double sum = 0;
			/*int money = 0;
			for (int i = 0; i < type; i++){
				money += vec[i].price * vec[i].weight;
				sum += vec[i].weight;
				if (money > total){
					sum -= (money - total) * 1.0 / vec[i].price;
					break;
				}
			}*/

			for (int i = 0; i < type; i++){
				int temp = vec[i].price * vec[i].weight;
				if (temp <= total){
					sum += vec[i].weight;  //能购买就全买
					total -= temp;
				}
				else{
					sum += 1.0 * total / vec[i].price;
					total = 0;
				}			
			}
			printf("%.2lf\n", sum);
		}
	}
	return 0;
}










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值