贪心算法专题(1)--HDU1009

来源:互联网 发布:直播软件xsplit 编辑:程序博客网 时间:2024/04/30 15:39


FatMouse' Trade

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


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

Sample Output
13.33331.500
 

Author
CHEN, Yue
 

Source
ZJCPC2004

题目出处:HDU--1009
把cxlove大佬的贪心专题刷一遍,算是复习一下贪心,也顺便补一补博客。

http://blog.csdn.net/acm_cxlove/article/details/7724021--by  cxlove


题目大意:fatmouse需要用自己手中的猫粮去跟猫交易javabean-就是咖啡豆,共有n个房间,每个房间与一只猫,第  i 个房间里面,fatmouse可以支付 F[i] 磅的猫粮去交换得到 J[i] 磅的javabean,注意的是:fatmouse 可以不遍历所有房间,也不用一次性在某一房间交易所有该房间猫所需的猫粮,支付了多少就能够按照比例得到多少,所以当然是优先选择性价比比较高的房间。


思路:结构体--房间,对于每一个房间有三个属性值,即:交易所需猫粮-F[i]、可获得的javabean-J[i]、可获得的javabean与所需猫粮-F[i]的比例,也就是性价比-value[i]。然后对按照性价比从大到小的顺序对房间进行排序,fatmouse从头到尾依次遍历即可,最后访问的房间可能会有猫粮不够,只能交易部分的情况,此时只需按比例获取即可。


代码:

/* *Li Wenjun *Email:1542113545@qq.com */#include<stdio.h>#include<string.h>#include<math.h>#include <iostream>#include <algorithm>#include <cstring>#include <cmath>#include <queue>#include <vector>#include <cctype>#include <stack>#include <list>#include <cstdlib>#include <set>#include <map>using namespace std;const int MAXN = 1005;struct NODE{    int J,F;    double values;}room[MAXN];int M,n;bool cmp(NODE x,NODE y){    return (x.values>y.values);}int main(){    while( cin >> M >> n,M!=-1)    {        for(int i=0;i<n;i++)        {            cin >> room[i].J >> room[i].F;            room[i].values = 1.0*room[i].J/room[i].F;        }        sort(room,room+n,cmp);        double ans=0;        for(int i=0; i<n;i++)        {            if(M >= room[i].F)            {                M-=room[i].F;                ans+=room[i].J;            }            else            {                ans+=M*room[i].values;                break;            }        }        printf("%.3f\n",ans);    }    return 0;}





0 0
原创粉丝点击