HDOJ 1009. Fat Mouse' Trade 贪心 结构体排序

FatMouse' Trade

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 56784    Accepted Submission(s): 19009
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
 
Source
 
        简单水题,相同的题目有:HDOJ 1009、ZOJ 2109。
        题目大意:胖老鼠拿M磅猫粮去贿赂守卫仓库的猫,仓库有N个房间,第i个房间有J[i]磅JavaBean且需要贿赂F[i]磅猫粮。可以选择只要J[i]*a%磅JavaBean,这样只需要贿赂F[i]*a%磅猫粮。请计算可以换取JavaBean的最大数量。
        我们可以用P[i]来表示每磅猫粮能换多少JavaBean,即J[i]/F[i],可以看做性价比。对P排个序,优先选择性价比最高的进行交易,算是贪心算法的思想。需要用到结构体排序。
 
 #include <stdio.h>
#include <algorithm>
struct room{int J,F;double P;}a[];
bool cmp(const room&a, const room&b){return a.P>b.P;} int main()
{
int M, N;
while(scanf("%d%d",&M,&N)&&~M) {
for(int i=; i<N; i++) {
scanf("%d%d", &a[i].J, &a[i].F);
a[i].P=(double)a[i].J/a[i].F;
}
std::sort(a,a+N,cmp);
double maxf=.;
for(int i=; i<N; i++)
if(M>a[i].F) {
M-=a[i].F;
maxf+=a[i].J;
}else{
maxf+=(double)a[i].J * M /a[i].F;
break;
}
printf("%.3f\n",maxf);
}
return ;
}
上一篇:vue data中的对象的属性如何使用watch监听


下一篇:据说是Flord算法