FatMouse’ Trade
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 76179 Accepted Submission(s): 26096
Problem Description
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] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[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] and F[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
Author
CHEN, Yue
题意
意思是有一个老鼠想吃食物,但是食物被猫看守,老鼠可以用诱饵引诱猫,这样就能去吃食物。不同食物需要消耗的诱饵不一样,价值也不一样。求最多能获得多大的价值。
(最奇葩的是,如果用3个诱饵能完全吃完食物,你用1个诱饵就能吃1/3个食物。!!!,不过好像也很科学哎。)
这就是个贪心问题,我们肯定要优先选择最高性价比的食物。
解题思路
首先按照性价比排序,优先选择最高性价比的食物。
定义一个 double 型变量 sum=0,计算能获得食物的价值,定义一个 w 统计剩余的诱饵。
查看自己所剩余的诱饵够不够完全吃完食物,如果能,就扔出所需要的诱饵,如果不能就全部扔出去。 然后sum=sum+这次获得的食物价值。
AC代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
struct sub
{
int v,w;
double percent;
};
int w,n;
double sum=0;
sub arr[2003];
bool cmp(sub a,sub b){
return a.percent>b.percent;
}
void f(sub a){
if(w>=a.w){
w-=a.w;
sum+=a.v;
}
else{
sum+=w*a.percent;
w=0;
}
//printf("test case is %.3lf and has w=%d\n",sum,w);
}
int main(){
while(~scanf("%d %d",&w,&n)&&w!=-1){
sum=0;
for(int i=0;i<n;++i){
scanf("%d %d",&arr[i].v,&arr[i].w);
arr[i].percent=arr[i].v*1.0/arr[i].w;
}
sort(arr,arr+n,cmp);
for(int i=0;i<n;++i)
f(arr[i]);
printf("%.3lf\n",sum);
}
}