hdu1009 FatMouse' Trade 贪心算法

题目描述:老鼠去找猫用猫粮换咖啡豆,猫都住在一个仓库里面,里面有很多房间,每个房间都装得有咖啡豆j[i],但是需要缴纳一定的咖啡豆f[i],老鼠不需要全部拿完i-th间所有的咖啡豆j[i],如果它缴纳f[i]*a%的猫粮,就可以获得j[i]*a%的咖啡豆,所有的数据都是不超过1000的非负整数。

现在要求老鼠可以换到多少的咖啡豆,结果保留3位小数.

我们买东西都会遵循的一个原则:花费最少,收获最大,这个是解决这个题目的关键 .。
我们每次都尽量取完咖啡豆最多,消耗猫粮最少的房间的所有东西,对于比例的问题,应该是放在当所持有的猫粮少于房间所需要的猫粮时才会考虑。
由此引出一个关键步骤:排序。
设置一个结构体表示房间:

Struct Hourse{
    int j;//里面的咖啡豆
    int f;//需要的猫粮
}

我们排序的依据是咖啡豆与猫粮的比例,比例越高,那么这个房间就应该先被考虑。
构造一个比较函数cmp()

bool cmp(hourse a,hourse b){
    if((a.j/(double)a.f)>(b.j/(double)b.f))
        return true;
    else
        return false;
}

好,上题目:
FatMouse’ Trade
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 54406 Accepted Submission(s): 18244

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

上代码:

#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#define maxn 1005

using namespace std;

struct Hourse{
    int j,f;
};

int m,n;
double jb;
Hourse  hourse[maxn];

bool cmp(Hourse a,Hourse b){
    if((a.j/(double)a.f)>(b.j/(double)b.f))
        return true;
    else
        return false;
}


int main(){
  while(scanf("%d%d",&m,&n)!=EOF&&m!=-1&&n!=-1){
    jb=0;
    memset(hourse,0,sizeof(hourse));
    for(int i=0;i<n;i++){
        scanf("%d%d",&hourse[i].j,&hourse[i].f);
    }
    sort(hourse,hourse+n,cmp);
    //关键部分
    for(int i=0;m!=0;i++){
        if(m>=hourse[i].f){
            m-=hourse[i].f;
            jb+=hourse[i].j;
        }
        else{
            jb+=hourse[i].j*((m/(double)hourse[i].f));
            m=0;
        }
    }
    printf("%.3lf\n",jb);
  }
  return 0;
}







你可能感兴趣的:(C++,ACM,贪心)