贪心 --- 模板题

FatMouse' Trade

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


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

【题目来源】

ZJCPC2004

【题目大意】

jack有M磅猫食,他想用这些猫食来换他最喜爱的javabeans,在他面前有n个房间,每个房间上表明了:J颗豆可以用F磅猫食来换取。

让你选择最优的方案换取最多的豆。

【题目分析】

贪心的水题,先排序,然后就按顺序选,直至将所有的猫食都换光。

#include<stdio.h>
#include<algorithm>
using namespace std;
struct Node
{
    int a,b;
    double c;
};
Node node[1010];

bool cmp(Node a,Node b)
{
    return a.c>b.c;
}

int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m),n!=-1&&m!=-1)
    {
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&node[i].a,&node[i].b);
            node[i].c=(double)node[i].a/(double)node[i].b;
        }
        sort(node,node+m,cmp);
        double sum=0;
        for(int i=0;i<m;i++)
        {
            if(n<=0)
                break;
            else
            {
                if(n>node[i].b)
                {
                    sum+=node[i].a;
                    n-=node[i].b;
                }
                else
                {
                    sum+=n*node[i].c;
                    break;
                }
            }
        }
        printf("%.3lf
",sum);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/crazyacking/p/3753688.html