HDU 1009 FatMouse' Trade 详解

FatMouse' Trade


FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J i i pounds of JavaBeans and requires F i i pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J i i* a% pounds of JavaBeans if he pays F i i* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.
Input
The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J i i and F i i respectively. The last test case is followed by two -1's. All integers are not greater than 1000.
Output
For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.
Sample Input
5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1
Sample Output
13.333
31.500

详细题解:
该题为背包问题。
大致题意为:有m个房间,每个房间都有一只小猫咪守着,小老鼠共有n个可付出的代价,在某个房间,小老鼠可以以一定比例付出代价获得相应的收获,所以该题是要求解小老鼠可以获得的最大的收获。
具体分析:由于每个房间都包含了小老鼠需要付出的代价、小老鼠最多可以获得的收获和该房间的比例三个元素,所以在此采用结构体的构造。接下来的求解就比较容易了,当我们输入每个房间的代价和收获后,分别计算每个房间的比例(收获/代价),并把每个房间的比例按从大到小的顺序排列(这一步的意义:小老鼠最终要获得最大的收获,达到的方法是用最少的代价获得最多的收获,而房间比例大时,相应的可以达到这种效果),然后从比例最大的房间开始获得收获,如果最后的代价不足以获得这个房间内的所有收获,这是按比例获得代价相应的收获。

附上AC代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct Tode{
	int shouhuo,daijia;
	double percent;
}mouse[1005];
int ss(Tode a,Tode b){
	return a.percent>b.percent;
}
int main(){
	int m,n,i,j;
	while(cin>>n>>m&&(n!=-1||m!=-1)){
		for(i=0;i<m;i++){
			cin>>mouse[i].shouhuo>>mouse[i].daijia;
			mouse[i].percent=(double)mouse[i].shouhuo/mouse[i].daijia;
		}
		sort(mouse,mouse+m,ss);
		double sum=0;
		for(i=0;i<m;i++){
			if(n>mouse[i].daijia){
				sum+=mouse[i].shouhuo;
				n-=mouse[i].daijia;
			}
			else{
				sum+=n*mouse[i].percent;
				n=0;
				break;
			}
		}
		printf("%.3lf\n",sum);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值