【贪心】FatMouse' Trade

来源:互联网 发布:淘宝订单处理流程图 编辑:程序博客网 时间:2024/05/10 22:06


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 37 24 35 220 325 1824 1515 10-1 -1
          

simple output

13.333
31.500


【解题报告】

        本题也是经典的贪心算法。本题三次才AC。第一次提交测试数据可以过。主要是几种特殊情况没有考虑。题目中明确指出输入的两个数据是非负数,所以说可以是为0的。一开始没有想到这点,程序出现错误。本次运用贪心策略,每次只选取单位钱获得java最多的。由于可以选取部分,所以本题一定是可以凑成正好的~ 每次从单位价值最大的开始取~ 如果能取完~ 就都拿完,如果不能的话~ 在尽可能多的情况下拿,只要本题注意特殊情况~ AC还是不难的。


【自己的源代码】

#include<iostream>#include<algorithm>#include<stdio.h>using namespace std;struct java_list {    int obt;    int pay;    double eve;};bool cmp(java_list a, java_list b){    return a.eve>b.eve;}int main (void){    struct java_list java[1000];    int m,n,i,t,k;    int money;    double sum;    double ling=0;    while((cin>>m>>n)&&(m!=-1)&&(n!=-1)){        if((m!=0)&&(n==0)){            printf("%.3f\n",ling);        }        else{            money=0;            k=0;            sum=0;            for(i=0;i<n;i++){                cin>>java[i].obt;                cin>>java[i].pay;                java[i].eve=(double)java[i].obt/(double)java[i].pay;            }            sort(java,java+n,cmp);            while(money<m){                money+=java[k].pay;                sum+=java[k].obt;                k++;            }            if(money>m){                k--;                sum-=java[k].obt;                money-=java[k].pay;                sum=sum+(m-money)*java[k].eve;                printf("%.3f\n",sum);            }            else if(money==m){                printf("%.3f\n",sum);            }        }    }    return 0;}



       









0 0
原创粉丝点击