您的位置:首页 > 其它

HDU 1009 FatMouse' Trade

2016-11-13 20:52 387 查看

题目

Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u

Submit

Status

Practice

HDU 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

代码

先给出我的AC代码,然后一段一段代码讲

AC代码:

#include<stdio.h>
int main(){
int a[1001],b[1001];
int i,m,n,j,temp;
double sum,x;
while(scanf("%d%d",&m,&n),m!=-1&&n!=-1){
for(i=0;i<n;i++)
scanf("%d%d",&a[i],&b[i]);
for(i=0;i<n;i++)
for(j=0;j<n-1;j++){
if(a[j]*b[j+1]<a[j+1]*b[j]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
}
sum=0;
for(i=0;i<n;i++){
if(b[i]>m){
x=(double)m*a[i]/b[i];
sum+=x;
break;
}
if(b[i]<=m) {
sum+=a[i];
m-=b[i];
}
}
printf("%.3lf\n",sum);
}
return 0;
}


题解

题目大意是:一个人手里有m个cat food,然后有n个房间

其中每个房间有a[i]个JavaBeans ,和换取所对应需要的b[j]个cat food,非常需要注意的是假如手中的cat food足够时,必须交足该房间所需的cat food数,不足时按比例获得JavaBeans 数。

我的想法是通过比例的大小来满足贪心的要求,先通过比例将输入的a[i]与b[j],从新排序,使其新顺序满足从下标为0到下标结束时,单位换取的JavaBeans 量是最多的。

下面解剖代码:

for(i=0;i<n;i++)
scanf("%d%d",&a[i],&b[i]);


接受多组房间的JavaBeans数 ,和换取所对应需要的cat food数。

for(j=0;j<n-1;j++){
if(a[j]*b[j+1]<a[j+1]*b[j]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
}


按照比例大小进行排序,temp是中间值,满足两个数组交换值,注意!!a[]与b[]一定要同时换,因为a[]与b[]是一一对应的。

if(b[i]>m){
x=(double)m*a[i]/b[i];
sum+=x;
break;
}


该段代码是在手里的cat food不足的情况下时,能换取的JavaBeans 数

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDU 杭电oj