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.
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.
5 3 7 2 4 3 5 2 20 3 25 18 24 15 15 10 -1 -1
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;
}