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
部分背包问题,这里我们可以取走物品的一小部分(也就是可以切割),那么我们就可以根据 物品的价值/物品的重量 (这个可以根据题目转换)那么这一个题目其实就是
根据 食物重量/所需的猫粮 来进行我们的贪心策略。
很容易分析得到,我们需要选择 食物重量/所需的猫粮 这个比值越大越好的,所以我们需要根据这个来进行排序,然后从上往下选择食物,直到我们手中的猫粮<0
AC代码如下:
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
struct wareroom{
int Jweight;
int Fpounds;
bool operator < (const wareroom &ware)
{
return double(Jweight)/Fpounds>double(ware.Jweight)/ware.Fpounds;
}
};
void setroom(int n,wareroom a[])
{
for(int i=0;i<n;i++)
cin>>a[i].Jweight>>a[i].Fpounds;
return ;
}
const int maxn=1e5+5;
wareroom ware[maxn];
int main()
{
int M,N;
while(cin>>M>>N && (M!=-1 && N!=-1))
{
setroom(N,ware);
sort(ware,ware+N);
double JtotalWeight=0;
for(int i=0;i<N;i++)
{
if(M>=ware[i].Fpounds)
{
M-=ware[i].Fpounds;
JtotalWeight+=ware[i].Jweight;
}
else if(M<ware[i].Fpounds)
{
JtotalWeight+=double(M)/ware[i].Fpounds*ware[i].Jweight;
break;
}
}
cout<<fixed<<setprecision(3);
cout<<JtotalWeight<<endl;
}
return 0;
}