HDU1009 FatMouse' Trade - 贪心

题目连接

http://acm.hdu.edu.cn/showproblem.php?pid=1009

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

题意

老鼠有M磅猫粮,现在想找猫换豆子,每个猫舍有Ji磅豆子,而且价值Pi磅的猫粮,老鼠每次都可以按百分比只买其中的一部分。

题解

基础的完全背包问题,按照J[i]/P[i]的大小进行排序,然后钱不够不能全部买走的时候只买一部分花光剩余的猫粮即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 10010;
struct node{
double f,p,w;
}point[maxn];
bool cmp(node a,node b){
return a.w>b.w;
}
int main(){
int n=0,m=0;
while(~scanf("%d%d",&m,&n)){
if(m==-1 || n==-1){
break;
}
for(int i=0;i<n;++i){
scanf("%lf%lf",&point[i].f,&point[i].p);
}
for(int i=0;i<n;++i){
point[i].w = point[i].f/point[i].p;
}
sort(point,point+n,cmp);
double ans=0;
for(int i=0;i<n;++i){
if(m-point[i].p>=0){
ans+=point[i].f;
m-=point[i].p;
}
else{
ans+=(m/point[i].p)*point[i].f;
break;
}
}
printf("%.3lf\n",ans);
}
}