題目描述
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.
輸入
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.
輸出
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.
樣例輸入
4 2 4 7 1 3 5 5 4 8 3 8 1 2 2 5 2 4 -1 -1
樣例輸出
2.286 2.500
思路:
貪心算法,具體思路可以看代碼註釋部分
#include<bits/stdc++.h>
using namespace std;
struct fat
{
int j; //食物
int f; // 貓糧
};
bool cmp(fat a, fat b)
{
return ((double)a.f/a.j) < ((double)b.f/b.j); //數值越小,表示可以用更少的貓糧換取更多的食物
}
int main()
{
int m, n; //分別表示 m 磅的貓糧 和 n行數據
while(cin >>m >> n && m!=-1 && n!=-1)
{
struct fat s[n];
for(int i=0;i<n;i++)
{
cin >> s[i].j >> s[i].f;
}
sort(s, s+n, cmp);
double ans = 0.0;
for(int i=0;i<n;i++)
{
if(m>=s[i].f) //當準備的貓糧可以換取一個房間的所有食物
{
ans += s[i].j;
m -= s[i].f;
}
else //準備的貓糧可以換取一個房間的部分食物,按比例分配,此時,準備的貓糧完全換出了,可以直接退出循環
{
ans += (double)m / s[i].f * s[i].j;
break;
}
}
printf("%.3f\n", ans);
}
return 0;
}