HDU 1009 FatMouse' Trade(贪心)

时间:2023-03-09 21:48:05
HDU 1009 FatMouse' Trade(贪心)

FatMouse' Trade

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
Answer
老鼠手上有n的猫粮,猫手上有m份的鼠粮(其实是绿豆...),这m份绿豆分别给出绿豆的量和价格,求老鼠用n的猫粮最多换到多少绿豆。
先根据单价(每份绿豆)排序,然后从单价小的开始贪心往后,最后输出保留三位小数。
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#include <map>
#define PI acos(-1.0)
#define ms(a) memset(a,0,sizeof(a))
#define msp memset(mp,0,sizeof(mp))
#define msv memset(vis,0,sizeof(vis))
using namespace std;
//#define LOCAL
struct Node
{
int num;//绿豆数量
int need;//需要猫粮
}t;
int cmp(Node n1,Node n2)//单价从小到大
{
return 1.0*n1.need/n1.num<1.0*n2.need/n2.num;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
ios::sync_with_stdio(false);
int n,m;//猫粮,组数
vector<Node> v;
while(cin>>n>>m&&n!=-)
{
v.clear();
double ans=;
for(int i=;i<m;i++)
cin>>t.num>>t.need,v.push_back(t);
sort(v.begin(),v.end(),cmp);
for(int i=,siz=v.size();i<siz;i++)
{
t=v[i];
if(t.need<=n)ans+=t.num,n-=t.need;
else {ans+=n/(1.0*t.need/t.num);break;}
}
printf("%.3lf\n",ans);
}
return ;
}