HDOJ----------1009

时间:2024-07-26 22:06:02

题目:

FatMouse' Trade

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 52127    Accepted Submission(s):
17505

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
分析:本题用到的是贪心算法,猫粮换成Java豆的比例越大应越先被兑换。在此我通过每个结构体保存每个屋子中的J[i]与F[i]及其兑换比例scale,然后利用sort将所有结构体中的scale按从大到小进行排序。之所以这样做的原因是,根据scale排序后,不会打乱原先每个屋子J[i]与F[i]及其兑换比例scale的对应关系,即排序的过程中结构体的结构不发生变换,只不过是根据结构体中的scale变量给所有结构体排一下序而已。最后的换Java豆的工作也简单多了。
代码如下:
 #include<cstdio>
#include<algorithm>
using namespace std; const int maxN = + ; struct warehouse{
int J;
int F;
double scale;
}House[maxN]; bool cmp(const struct warehouse a, const struct warehouse b) {
return a.scale > b.scale;
} int main() {
int M, N;
double ans;
while(scanf("%d %d", &M, &N) == ){
if(M == - && N == -) break;
//输入
for(int i = ; i < N; i++) {
scanf("%d %d", &House[i].J, &House[i].F);
House[i].scale = (double)House[i].J/House[i].F;
}
//将所有屋子中的猫粮与Java豆兑换的比例排序
sort(House, House + N, cmp);
// for(int i = 0; i < N; i++)
// printf("%.3lf\t", House[i].scale);
//按比例从大到小分配猫粮
ans = 0.0;
int pos = ;
while(M > && N > ){//猫粮换完,或者Java豆已经没有时应该终止循环
if(M > House[pos].F)
ans += House[pos].J; //若猫粮充足,直接将屋子的Java豆兑换下来
else
ans += (double)House[pos].J * M / House[pos].F; //能兑换的猫粮不足,这时应该按比例来兑换Java豆
M -= House[pos].F;
N--;
pos++;//到下一家
}
//输出
printf("%.3lf\n", ans);
}
return ;
}

                                                                2015-07-02文

相关文章